What's the risk of modifying the state without setState?

时间:2019-02-18 00:18:16

标签: javascript reactjs

I know that modifying directly the state without setState(...) won't update the UI automatically, but I can still do this:

this.state.myValue = "foo";
this.forceUpdate();

I am also aware that React waits for certain moments to update several components in a single pass, but are there really any compelling reason why I shouldn't alter directly the state without setState(...)?

There are 2 scenarios where altering directly the state would be beneficial for me:

  • If I have to modify an element of a very long array, the performance gain from the 'cluster update' of setState(...) would be negligible compared to the performance gain from not shallow copying the entire array every time.

  • If I have 2 references to the same object in 2 different properties of the state and I want to modify this object, I would prefer to do this modification on a single property, but if I use setState(...) I would copy the object and lose the reference.

Thank you for your help.

2 个答案:

答案 0 :(得分:1)

If you modify state directly and at same time some other logic also updates state. It is not guaranteed that you have correct state or other logic is having correct state.

It might give you unpredictable results and behavior. So it is always advisable to use only setState() as this is async and update state immutably.

答案 1 :(得分:0)

不使用setState()来修改状态的风险是:

  • 直接更改状态不会让您调用render()方法和其他生命周期方法。
  • setState()更改了DOM,否则将保持不变
  • 文档说:状态是在应用更改时对组件状态的引用。它不应该直接突变。相反,更改应通过根据状态和道具的输入来构建新对象来表示。