简体   繁体   English

改变反应状态的单个变量

[英]Change single variable of react state

Is it allowed to assign a single variable of react component state like this.state.foo = "bar" without calling setState? 是否允许在不调用setState的情况下分配像this.state.foo = "bar"这样的反应组件状态的单个变量? I need to change part of the state in multiple places, and I'm unable to use object spread operator and Object.assign is too verbose. 我需要在多个地方更改部分状态,并且我无法使用对象扩展运算符和Object.assign太冗长。 How to change just a part of the state without redefining the whole state? 如何在不重新定义整个州的情况下改变国家的一部分?

You should use setState rather than instance variables because it is important that React knows about state changes so that it can trigger renders appropriately. 您应该使用setState而不是实例变量,因为React了解状态更改以便它可以适当地触发渲染很重要。

Because of the diffing algorithm React uses on the DOM it is efficient to call setState as often as you like. 由于React在DOM上使用的差异算法,因此可以根据需要随时调用setState

Note that calling setState on one variable will leave the others unchanged: 请注意,在一个变量上调用setState会使其他变量保持不变:

this.setState({ foo: 'bar' }); // Does not change foo2

就像那样

this.setState({ foo: 'bar' )};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM