React 里直接修改 this.state 和调用 setState() 修改 state 的值有什么区别?

setState 方法除了修改 this.state 的值还做了什么?

阅读 23.5k
2 个回答

使用对this.state赋值并没有什么作用,官方提醒,应该把this.state当成不可变变量。
而使用this.setState方法,会触发异步修改状态,状态改变的同时,会重新执行一次willUpdate,render等流程。需要注意的是,避免在执行完this.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.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏