更新componentWillreceiveProps中的状态值

时间:2017-07-19 06:47:21

标签: reactjs

class Filters extends Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  componentWillReceiveProps(nextProps) {
    nextProps.dataAsProp.map(data => {
      if (data.productList.length == 0)
       this.setState({ count: this.state.count + 1 });
     });

}

如何更新每个数据的计数值,而该数据的生产者是一个空数组。它只打印一个。它不计入dataAsProp中的所有数据。

1 个答案:

答案 0 :(得分:1)

原因是setState是异步的,所以我们无法预测循环迭代中的更新值。

的变化:

1.不要多次执行setState,首先计算该值,然后在最后更新状态计数值一次。

2.使用forEach代替map

像这样写:

componentWillReceiveProps(nextProps) {

    /*put the check here, perform this operation only when there a change between nextProps and prev props values*/

     let count = 0;
     nextProps.dataAsProp.forEach(data => {
        if (data.productList.length == 0)
            count++;
     });
     this.setState({ count });
}

选中answer for difference between forEach and map

检查此答案以获取有关setState的异步行为的更多详细信息:

Why calling setState method doesn't mutate the state immediately?

相关问题