React.js having state based on other state

前端 未结 3 1203
悲&欢浪女
悲&欢浪女 2021-02-01 16:22

I\'m running into some problems with React.js and the state not being immediately set when calling setState(). I\'m not sure if there are better ways to approach this, or if it

3条回答
  •  萌比男神i
    2021-02-01 16:44

    Yes, setState is asynchronous, so this.state won't be updated immediately. Here are the unit tests for batching, which might explain some of the details.

    In the example above, alarmSet is data computed from the alarmTime and elapsedTime state. Generally speaking, computed data shouldn't be stored in the state of the object, instead it should be computed as-needed as part of the render method. There is a section What Shouldn’t Go in State? at the bottom of the Interactivity and Dynamic UIs docs which gives examples of things like this which shouldn't go in state, and the What Components Should Have State? section explains some of the reasons why this might be a good idea.

提交回复
热议问题