【发布时间】:2016-12-15 20:39:13
【问题描述】:
很难弄清楚我在这里做错了什么......而且我敢肯定这是我错过的一些简单的事情。只要传递到此 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");
};
}); }
非常感谢您的帮助!
【问题讨论】:
-
何时调用
countCategories? -
先计算值,再设置..
标签: reactjs