gpt4 book ai didi

javascript - React.js setState of objects 属性从数组

转载 作者:行者123 更新时间:2023-11-30 15:19:15 26 4
gpt4 key购买 nike

现在我需要递增/递减状态对象数组的属性值。我已经尝试将我想到的所有内容都扔给 setState。有时它没有抛出任何错误,但也没有更新值现在我收到错误消息:

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)
}

最佳答案

你你克隆了一个状态对象,你可以直接修改它并回退到状态

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

}

如果您想知道[...this.state.products] 是什么意思,请查看此答案:What is the meaning of this syntax "{...x}" in Reactjs

关于javascript - React.js setState of objects 属性从数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43997577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com