When to use functional setState

后端 未结 3 897
一生所求
一生所求 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:36

    TL;DR: Functional setState is mainly helpful to expect correct state update when multiple setStates are triggered in a short interval of time where as conventional setState does reconciliation and could lead to unexpected state.

    Please check this wonderful article on Functional setState to get a clear understanding

    And here is the WORKING DEMO

    Firstly, you are trying to do different things in each of your cases, you are assigning pics in one and concatenating pics in another.

    Lets say this.state.pictures contain [1, 2, 3] and pics contain [4, 5, 6]

    this.setState({pictures: pics})

    In the above case this.state.pictures will contain the pics i.e this.state.pictures = [4, 5, 6]

    this.setState(prevState => ({
       pictures: prevState.pictures.concat(pics)
    }))
    

    Whereas in the above snippet, this.state.pictures will contain the previous pictures + pics i.e this.state.pictures = [1, 2, 3, 4, 5, 6]

    Either way you can tweak it to meet your API needs, if it's like a paginated response the you are better off concatenating the results on each request, else if you get the whole array each time just assign the whole array.

    Conventional setState VS Functional setState

    Now, your question mainly is probably whether to use setState with an object or with a function.

    People use both of them for different reasons, now the functional setState is said to be safe because React does something called a reconciliation process where in it merges multiple objects inside setState when triggered frequently or concurrently and applies the changes in one shot, kind of like a batch process. This could potentially lead to some unexpected results in scenarios like below.

    EXAMPLE:

    increaseScoreBy3 () {
     this.setState({score : this.state.score + 1});
     this.setState({score : this.state.score + 1});
     this.setState({score : this.state.score + 1});
    }
    

    As you would expect the score to be incremented by 3 but what React does is merge all the objects and update the score only once i.e incrementing it by 1

    This is one of the cases where functional callback shines because reconciliation does not happen on functions and executing the below code will do things as expected i.e update score by 3

    increaseScoreBy3 () {
     this.setState(prevState => ({ score: prevState.score + 1 }));
     this.setState(prevState => ({ score: prevState.score + 1 }));
     this.setState(prevState => ({ score: prevState.score + 1 }));
    }
    

提交回复
热议问题