1

预期效果:点击按钮->调用函数add->添加对象this.color到数组products-colors组件App中的属性。示例: colors: [{color:" green "}, {color:" black "}]->colors: [{color: "green"}, {color: "black"}, {color: "red "}]

错误:TypeError:无法读取未定义的属性“推送”

应用程序

class App extends React.Component {
  state = {
    products: [
      { id: 0, colors: [{color:"green"}, {color:"black"}], desc: "some desc" },
      { id: 1, colors: [{color:"yellow"}, {color:"purple"}], desc: "some desc1" }
    ],
    index: null
  };


  add = (newColor) => {
    let newProducts = [...this.state.products]
    newProducts[index].colors.push(newColor);
    this.setState({products: newProducts});
  }

   select = (index) => {
    this.setState({
      index: index
    })
  }


  render() {
    <div>
      <ul>
        {
          this.state.products.map((product, index) => (
            <Product
              key={product.id}
              product={product}
              select={() => this.select(index)}
            />
          ))
        }
      </ul>
      <Details
        add={this.add}
      />
    </div>
  }
}

细节

class Details extends React.Component {

  click1 = () => {
      this.color = {
          color: 'red'
      }

      this.props.add(this.color);
  }



  render() {
    <div>
        <button onClick={this.click1}></button>
    </div>
  }
}
4

2 回答 2

2

更改此行:

newProducts[this.state.index].colors.push(newColor);

但是,如果要根据先前的状态设置状态,则应该使用setState 的回调模式,因此:

this.setState(prevState => {
  let newProducts = [...prevState.products];
  newProducts[prevState.index].colors.push(newColor);
  return {products: newProducts};
});
于 2019-06-18T00:26:07.617 回答
0

index的是undefined。所以它正在访问 index 的数组元素undefined

 const arr = [3, 2]
 arr[undefined] === undefined // true

所以我会

 add = (newColor) => {
   const { index } = this.state;

   if (index) {
     this.setState(prevState => {
       const newProducts = [...prevState.products];
       newProducts[index].colors.push(newColor);

       return { products: newProducts };
     });
   }
 }
于 2019-06-18T01:17:15.820 回答