reactjs - react : Syntax for calling setState in Switch Return

标签 reactjs

很难弄清楚我在这里做错了什么......而且我确信我错过了一些简单的事情。只要传递到此 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/

相关文章:

javascript - 将 css 文件嵌入到内部 <style> 元素中

javascript - 如何使用 React.js 用类包围每个 X 元素

javascript - 在 React.js 应用程序中使用 freshdesk 反馈小部件

javascript - React store.getState 不是函数

javascript - React state/props 不会更新

javascript - 如何让我的菜单逻辑更简洁?

javascript - 如何根据 props 的值渲染组件?

node.js - Electron 和 React-BoilerPlate 白屏

javascript - Reactjs/Javascript 更新对象键名

javascript - com.facebook.react.bridge.readnativemap 无法在 React Native 中转换为 java.lang.string