setState 方法除了修改 this.state 的值还做了什么?
setState 方法除了修改 this.state 的值还做了什么?
在react的文档中有提到
Notes:
NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.
There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate(). If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.
3 回答1.8k 阅读✓ 已解决
1 回答1.6k 阅读✓ 已解决
4 回答1.6k 阅读✓ 已解决
2 回答2.4k 阅读✓ 已解决
1 回答2.5k 阅读✓ 已解决
2 回答1.3k 阅读✓ 已解决
2 回答1.5k 阅读✓ 已解决
使用对this.state赋值并没有什么作用,官方提醒,应该把this.state当成不可变变量。
而使用this.setState方法,会触发异步修改状态,状态改变的同时,会重新执行一次willUpdate,render等流程。需要注意的是,避免在执行完this.setState后马上读取this.state,此操作并不会获得最新修改的状态。