首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React将数据从映射子组件传递到新组件

React将数据从映射子组件传递到新组件
EN

Stack Overflow用户
提问于 2019-03-26 11:58:16
回答 4查看 56关注 0票数 0

我有一个购物目录,我想从子目录中获取数据,并将其传递给新组件。我已经从JSON映射了数据(稍后将成为api调用),我想从映射子组件中获得一些属性,即名称、价格和计数(这是组件的一部分,而不是原始数据)。

数据(名称/价格) -> mainComponent ->映射到childComponent(有计数)-> mainComponent

我应该使用表单吗?一些生命周期方法?redux?路由器?我真的不知道该怎么做。

数据

代码语言:javascript
运行
复制
const marketData = [
    {
        id: 1,
        name: "product1",
        price: "$2",
    },
    {
        id: 2,
        name: "product2",
        price: "$3",
    },
    {
        id: 2,
        name: "product3",
        price: "$3",
    }
]

父级

代码语言:javascript
运行
复制
import React, { Component } from 'react';
import MarketItem from './MarketItem.js'
import MarketData from './MarketData.js'


class MarketContainer extends Component {
  constructor() {
    super()
    this.state = {
      market: MarketData
    }
  }

  render() {
    const marketItems = this.state.market.map(item => <MarketItem key={item.id} product={item} />)

    return (
      <div>
          {marketItems}
      </div>
    );
  }
}

export default MarketContainer;

孩子

代码语言:javascript
运行
复制
import React, {Component}  from 'react';

class MarketItem extends Component {
constructor(props){
  super(props)
  this.state = {
        count : 0
      }
}


IncrementItem = () => {
  this.setState({ count: this.state.count + 1 });
}
IncrementItemBy10 = () => {
  this.setState({ count: this.state.count + 10 });
}

render(){
    return (
      <div className="MarketItem">
        <div className="market__content">
            <h1>{this.props.product.name + " " + this.props.product.price}</h1>   
        </div> 
            <div className="market__counter">
              <button className="market__button--minus" onClick={this.DecreaseItem}>-</button>
              <p>{this.state.count}</p>
              <button className="market__button--plus" onClick={this.IncrementItem}>+</button>
            </div>

      </div>
    );
  }
}
export default MarketItem;

在parent (marketContainer)中,我想从子组件中获取计数、名称和价格,创建一个新组件。我尝试过表单,但对我是否应该使用生命周期方法并不是很满意?redux?路由器?

EN

Stack Overflow用户

发布于 2019-03-26 13:05:39

您可以在MarketContainer中定义需要传递给其他子组件的计数和其他字段的状态。

我已经尝试包含代码来说明我将如何做到这一点。

代码语言:javascript
运行
复制
   //MarketData.js
    //after ajax request
    const marketData = [

      {
        id: 1, 
        name: "product1", 
        price: "$1"
      }, 

      {
        id: 2, 
        name: "product2", 
        price: "$2"
      }
    ]; 

    //We can format market data as per we need it in components

    const formattedMarketData = marketData.map(e => {
        e.count = 0; 
        return e;
    });





  //parent component
    //let us define all the things which we might need to pass to other components in here
    // ... 

    constructor()
    {
        super(); 
        this.state = {
            markets: formattedMarketData
        }

    }

    /* we are handling all state changes in parent component
     we have updated state in parent component
     we can deliver the changed state to any other components */
    IncrementItem = (id) => {
        this.setState((prevState) => {
            const markets = {...prevState.markets}; 
            const index = markets.findIndex(x => x.id ===id);
            markets[index].count = prevState.markets[index].count + 1; 
            return {
                markets: markets
            };
        });
    }

    DecrementItem = (id) => {
        this.setState((prevState) => {
            const markets = {...prevState.markets};
            const index = markets.findIndex(x => x.id ===id);
            markets[index].count = prevState.markets[index].count - 1; 
            return {
                markets: markets
            };
        });
    }

    render() {
        const marketItems = this.state.market.map(item => <MarketItem IncrementItem={this.IncrementItem} DecrementItem={this.DecrementItem} key={item.id} product={item} />)

        return (
          <div>
              {marketItems}
          </div>
        );
      }



//child component 

export default (props) => {
 const {IncrementItem, DecreaseItem, product} = props;
 <div className="MarketItem">
        <div className="market__content">
            <h1>{product.name + " " + product.price}</h1>   
        </div> 
            <div className="market__counter">
              <button className="market__button--minus" onClick={() => {DecreaseItem(product.id)}}>-</button>
              <p>{product.count}</p>
              <button className="market__button--plus" onClick={() => {IncrementItem(product.id)}}>+</button>
            </div>

      </div>
};
票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55349632

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档