改变React状态的首选方法是什么? [英] what is the preferred way to mutate a React state?
本文介绍了改变React状态的首选方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我在 this.state.list
中有一个普通对象列表,然后我可以使用它来呈现子列表。那么将对象插入 this.state.list
的正确方法是什么?
Let's say I have a list of plain objects in my this.state.list
that I can then use to render a list of children. What then is the right way to insert object into this.state.list
?
以下是我唯一的方法认为它会起作用,因为你不能直接改变文件中提到的 this.state
。
Below is the only way I think it will work because you can not mutate the this.state
directly as mentioned in the doc.
this._list.push(newObject):
this.setState({list: this._list});
这对我来说似乎很难看。有更好的方法吗?
This seems ugly to me. Is there a better way?
推荐答案
concat
返回一个新数组,所以你可以做到
concat
returns a new array, so you can do
this.setState({list: this.state.list.concat([newObject])});
另一种选择是React的 immutability helper
another alternative is React's immutability helper
var newState = React.addons.update(this.state, {
list : {
$push : [newObject]
}
});
this.setState(newState);
这篇关于改变React状态的首选方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文