很难弄清楚我在这里做错了什么......而且我确信我错过了一些简单的事情。只要传递到此 switch 调用的数据与每个类别匹配,就尝试增加状态计数器,但由于某种原因,计数器不会增加...
countCategories(cart) {
cart.map(function(item){
switch (item.type) {
case "beverage": return () => { this.setState({
countBeverage: this.state.countBeverage + 1
}); }
case "fruit": return () => { this.setState({
countFruit: this.state.countFruit + 1
}); }
case "vegetable": return () => { this.setState({
countVegetable: this.state.countVegetable + 1
}); }
case "snack": return () => { this.setState({
countSnack: this.state.countSnack + 1
}); }
default: return console.log("unknown category");
};
}); }
我也尝试过这种方式,但是当我这样调用它时,我认为我没有引用“this”:
countCategories(cart) {
cart.map(function(item){
switch (item.type) {
case "beverage": return this.setState({
countBeverage: this.state.countBeverage + 1
})
case "fruit": return this.setState({
countFruit: this.state.countFruit + 1
})
case "vegetable": return this.setState({
countVegetable: this.state.countVegetable + 1
})
case "snack": return this.setState({
countSnack: this.state.countSnack + 1
});
default: return console.log("unknown category");
};
}); }
非常感谢您的帮助!
最佳答案
就做这个吧伙计:
let food = [{type: "snack"},{type: "snack"},{type: "snack"},{type: "snack"},
{type: "veggi"},{type: "veggi"},{type: "veggi"},{type: "veggi"}]
let foodCount = {
veggiCount: this.state.veggiCount || 0,
snackCount: this.state.snackCount || 0,
beefCount: this.state.beefCount || 0,
fruitCount: this.state.fruitCount || 0
};
food.map(item => foodCount[item + "Count"]++ )
this.setState(foodCount)
这里重要的是,1. 一次,2. 计算完成后设置 State。避免在循环或迭代中设置状态,例如 for(...) setState()
关于reactjs - react : Syntax for calling setState in Switch Return,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38856852/