React:在Switch Return

时间:2016-08-09 17:16:06

标签: reactjs

很难弄清楚我在这里做错了什么......我确信这很简单,我很想念。只要传递到此切换调用的数据与每个类别匹配,只是尝试增加状态计数器,但由于某种原因,计数器不会递增...

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

非常感谢你的帮助!

3 个答案:

答案 0 :(得分:1)

假设您正在调用绑定到组件的countCategoriesthis的值是组件),在第一个应该工作的代码中,您可以将映射函数更改为箭头函数,因此它保留this函数的countCategories值。我注意到的另一个奇怪的事情是你通过返回应该改变状态的函数来创建一个函数数组,而不是实际改变状态:

countCategories(cart) {
  // Notice the change in the next line
  cart.map(item => {
    switch (item.type) {
      case "beverage": 
        // Set the state instead of returning a function that sets the state
        this.setState({
          countBeverage: this.state.countBeverage + 1
        });
        break;
      case "fruit": 
        this.setState({
          countFruit: this.state.countFruit + 1
        });
        break;
      case "vegetable": 
        this.setState({
          countVegetable: this.state.countVegetable + 1
        });
        break;
      case "snack": 
        this.setState({
          countSnack: this.state.countSnack + 1
        });
        break;
      default: 
        console.log("unknown category");
        break;
    };
  }); 
}

答案 1 :(得分:1)

这里一个重要的考虑因素是setState是异步的,所以你不能在同一个执行周期中读取值并递增它。相反,我建议创建一组更改,然后将它们应用于单个setState

下面我使用map迭代购物车并增加存储在克隆状态副本中的状态值(因为this.state应该被认为是不可变的)。然后一旦完成,状态就会更新。

let newState = Object.assign({}, this.state);
cart.map((item) => {
  // adapt type to state string -> snack to countSnack
  const type = item.type.replace(/^(.)/, (s) => 'count' + s.toUpperCase());
  newState[type] = (newState[type] || 0) + 1;
});

this.setState(newState);

请参阅Component API documentation中的说明了解详情

答案 2 :(得分:1)

做这个家伙:

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。计算完成后。避免在循环或迭代中设置状态,如for(...) setState()