【问题标题】:Making changes to a props array passed down from parent component in React Native更改从 React Native 中的父组件向下传递的 props 数组
【发布时间】:2015-12-07 02:11:36
【问题描述】:

我需要从子组件中更改嵌套对象数组。该数组作为来自父组件的道具传递下来,我想在列表中找到一个项目并对其进行更改,这样当我返回父场景时,更改将被保存。我有以下代码,但出现此错误: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()
}

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案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)
    

    所以总结一下,你需要从父级传递一个回调,在这种情况下 "changeCarItem" 并让子组件调用这个回调。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-28
      • 2018-07-31
      • 2021-10-20
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      相关资源
      最近更新 更多