React.js setState of objects property from array

时间:2017-05-16 09:30:25

标签: javascript arrays reactjs

Right now i need to increment/decrement a property value of state's array of objects. I have tried throwing everything that came to my mind to setState. At times it didnt throw any errors, but wasn't updating the value either Right now i get error message:

this.state.products[key] is undefined

constructor(props) {

    super(props)

    var products = [
        { name: "Motorhead glasses", price: 300, amount: 1 },
        { name: "Judaspriest glasses", price: 499, amount: 1 }
    ]

    this.state = { products: products }
    this.handleMinus = this.handleMinus.bind(this)

}


handleMinus(key) {
    var stateCopy = Object.assign({}, this.state);
    stateCopy.products = stateCopy.products.slice();
    stateCopy.products[key] = Object.assign({}, stateCopy.products[key]);
    stateCopy.products[key].amount += 1;
    this.setState({ [this.state.products[key].amount]: stateCopy });
    console.log(this)
}

3 个答案:

答案 0 :(得分:2)

You you clone a state object, you can modify it directly and setback to state

handleMinus(key) {
    var stateCopy = [...this.state.products];   /Create a copy of products array using spread operator syntax.
    stateCopy[key].amount += 1;
    this.setState({products : stateCopy });

}

If you wanna know what [...this.state.products] mean check this answer: What is the meaning of this syntax "{...x}" in Reactjs

答案 1 :(得分:0)

使用此项(查看评论):

handleMinus(key) {
    var stateCopy = this.state.products.slice();        //create a copy of products array
    stateCopy[key] = Object.assign({}, stateCopy[key])  //create a copy of object at that key
    stateCopy[key].amount += 1;                         //modify the value
    this.setState({products : stateCopy });             //update the state variable
}

您的代码也可以使用一小段更改,更改您使用setState更新state值的方式,使用此代码:

handleMinus(key) {
    var stateCopy = Object.assign({}, this.state);
    stateCopy.products = stateCopy.products.slice();
    stateCopy.products[key] = Object.assign({}, stateCopy.products[key]);
    stateCopy.products[key].amount += 1;
    this.setState(stateCopy);   //use this
}

答案 2 :(得分:0)

你正在为你的州制作不必要的浅层副本。

handleMinus(key) {
  const product = this.state.products[key];

  this.setState({
    products: [
      ...this.state.products,

      [key]: Object.assign({}, product, {
        amount: product.amount + 1
      })
    ]
  })
}