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


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

reactjs

wokaka 9 years, 10 months ago

可以关注下 react.js的一些专题 ,不知道是否对你有帮助;

马萨卡!? answered 9 years, 10 months ago

在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.

神无月的香霖 answered 9 years, 10 months ago

使用对this.state赋值并没有什么作用,官方提醒,应该把this.state当成不可变变量。
而使用this.setState方法,会触发异步修改状态,状态改变的同时,会重新执行一次willUpdate,render等流程。需要注意的是,避免在执行完this.setState后马上读取this.state,此操作并不会获得最新修改的状态。

useki_ answered 9 years, 10 months ago

Your Answer