通过分配设置状态

时间:2015-09-01 20:58:07

标签: reactjs

在反应中,有没有人想要通过赋值来设置变量的状态而不是调用setState(...)

示例:

// accessing state var directly
this.state.myVar = 'changed state'
// instead of calling setState
this.setState({myVar: 'changed state'})

对我而言,这似乎是一种反模式。但也许有一个很好的解释为什么有时候它是必要的?

2 个答案:

答案 0 :(得分:3)

It's necessary, because React has to know wether this.state is considered mutated. There is no dirty-checking in React. The state object is considered dirty when this.setState is called, and no further comparisons are made to its previous state. This answer might help explain this in more detail: Why is React's concept of Virtual DOM said to be more performant than dirty model checking?

答案 1 :(得分:0)

在这种情况下,直接设置(变异)状态将起作用: this.state.myVar = 'changed state'
但是,应该根据React docs

来避免
  

不要直接改变this.state,因为之后调用setState()可能会取代您所做的突变。将this.state视为不可变。

改变状态的主要问题是它阻止了一些React生命周期方法的工作。例如,React的shouldComponentUpdate()方法通常用于在处理大量组件时加速应用程序。如果状态已更新,则该方法允许您跳过重新呈现组件:

// Return false if you want to skip the `render()` method
shouldComponentUpdate: function(nextProps, nextState) {
  return this.state.myVar === nextState.myVar;
}

如果您要改变状态,上述操作将无效。 this.state.myVarnextState.myVar引用相同,因此上述内容将始终返回true