对从React Native中的父组件传递的props数组进行更改

时间:2015-12-07 02:11:37

标签: javascript reactjs react-native

我需要对子组件中的嵌套对象数组进行更改。数组作为父组件的道具向下传递,我想在列表中找到一个项目并对其进行更改,这样当我返回到父场景时,更改将被保存。我有以下代码,但是我收到此错误:undefined is not an object (evaluating \'this.state')。任何人都可以引导我朝正确的方向排除故障吗?

submitChange() {
  //update the cart list
  //hide the panel
  this.props.cartList.forEach(function(arrayItem) {
    if(arrayItem.prod.product === this.state.name) {
      arrayItem.quantityOrdered = this.state.quantity;
    }
    console.log(arrayItem.prod.product + " " + arrayItem.quantityOrdered)
  })
  console.log( " this item" + this.state.quantity + ", " + this.state.name)
  //this.props.hidePanel()
}

1 个答案:

答案 0 :(得分:1)

我不确定React-Native,但在React中你会有

父组件

getInitialState: function(){
    var carList = [.....];
 },

 changeCarItem: function(item){
    //first get the original 
    //find the item you want to modify 
    //after the item is found, make the change to your originalItem(carlist)
    //you need to use **this.setState()**, in-order to affect the main data
 }

 render: function(){
    <Child list={this.state.carList} changeCarItem={this.changeCarItem}>
    ......
 }

子组件

//perform your logic
//use this.props.changeCarItem(item)

总而言之,在这种情况下,您需要从父级传递回调 &#34; changeCarItem&#34;并让子组件调用此回调。

http://facebook.github.io/react/tips/communicate-between-components.html),看看这个