When to use functional setState

后端 未结 3 900
一生所求
一生所求 2020-11-22 10:13

I have been learning React over the past few days, looking at a few tutorials and explanations regarding the different ways in which you can write different elements. Howeve

3条回答
  •  时光取名叫无心
    2020-11-22 10:47

    A Quick answer:

    Always use functional form of setState().

    this.setState((state, props)=>({
        someValue: state.somevalue + 1
    }));
    

    This approach is less error-prone and helps to eliminate some very hard-to-find bugs. Even if react batches multiple such updates, each update is separate function call and subsequent updates will not cause some of these updates to be lost.

    The other approach

    this.setState({
    someValue: state.somevalue + 1
    });
    

    If repeated frequently, might cause some of the updates to be lost, since React batches such frequent updates.

提交回复
热议问题