反应从映射的子代到新组件的传递数据

时间:2019-03-26 03:58:16

标签: reactjs

我有一个购物目录,我想从孩子那里获取数据并传递给新组件。我已经从JSON映射了数据(后来称为api调用),我想从映射的子组件中获得一些支持,即名称,价格和计数(这是组件的一部分,而不是原始数据)< / p>

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

我应该使用表格吗?一些生命周期方法? redux?路由器?不太确定该怎么做。

数据

const marketData = [
    {
        id: 1,
        name: "product1",
        price: "$2",
    },
    {
        id: 2,
        name: "product2",
        price: "$3",
    },
    {
        id: 2,
        name: "product3",
        price: "$3",
    }
]

父母

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;

孩子

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;

在父级(marketContainer)中,我想从每个子级组件中获取数量,名称和价格,然后新建一个组件。我已经尝试过表单,但是对使用生命周期方法不满意吗? redux?路由器?

4 个答案:

答案 0 :(得分:0)

class MarketContainer extends Component {
   state = {
    count : 0
   }

   IncrementItem = () => {
   this.setState({count: count + 1})
   }

   DecreaseItem = () => {
   this.setState({count: count - 1})
   }

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

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

现在,当用户单击增量和减量图标时,可以在MarketItem组件上使用 IncrementItem DecreaseItem 道具。此外,我们正在从父组件传递 count 的值,以便您可以在子组件中显示。

答案 1 :(得分:0)

您需要在React中使用提升状态

答案 2 :(得分:0)

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

我试图添加代码来说明我将如何做。

   //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>
};

答案 3 :(得分:0)

我认为这是设计状态以保持与产品相关的计数的方法。

import React, { Component } from 'react';
import MarketItem from './MarketItem.js'

class MarketContainer extends Component {
 constructor() {
    super()
    this.state = {
          market:  [
            {
                id: 1,
                name: "product1",
                price: "$2",
                count:0,
            },
            {
                id: 2,
                name: "product2",
                price: "$3",
                count:0,
            },
            {
                id: 2,
                name: "product3",
                price: "$3",
                count:0,
            }
        ]
    }
}

IncrementItem = (i) => {
    let market = this.state.market;
    market[i].count += 1; 
    this.setState({market});
}

DecreaseItem = (i) => {
    let market = this.state.market;
    market[i].count -= (market[i].count > 0) ? 1: 0; 
    this.setState({market});
}

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

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

export default MarketContainer;

孩子

import React, {Component}  from 'react';

class MarketItem extends Component {
 constructor(props){
   super(props);
 }

 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.props.DecreaseItem(this.props.i)}>-</button>
              <p>{this.state.count}</p>

              <button className="market__button--plus" onClick={() => this.props.IncrementItem(this.props.i)}>+</button>
            </div>

      </div>
    );
 }
}

export default MarketItem;