我正在使用 ReactJS,这让我抓狂。
我正在尝试更新来自状态的对象
var state = this.state;
sku = data['sku'];
console.log(sku) //prints sku/06
console.log(state.sku) //prints sku/06
state.sku = sku;
console.log(state.sku) //prints sku/10
我查过了,只有一个电话在打。尽管我使用 flux 来更新商店,但此归因是在将操作发送到调度程序之前进行的。
这是怎么回事?
最佳答案
您是否尝试过使用 React 的 setState
函数更新状态?
var sku = data['sku'];
this.setState({sku: sku});
直接从 React 文档复制 https://facebook.github.io/react/docs/component-api.html
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.
关于Javascript 属性未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34020792/