what is the preferred way to mutate a React state?

前端 未结 4 1135

Let\'s say I have a list of plain objects in my this.state.list that I can then use to render a list of children. What then is the right way to insert object in

4条回答
  •  萌比男神i
    2020-12-07 10:19

    From the react docs (https://facebook.github.io/react/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous):

    Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

    So you should do this instead:

    this.setState((prevState) => ({
      contacts: prevState.contacts.concat([contact])
    }));
    

提交回复
热议问题