【发布时间】:2015-04-02 17:53:18
【问题描述】:
我正在使用 ReactJS。
我有一个有状态的组件(秒表容器)和多个无状态的子组件(秒表)。
在外部组件中,我正在做这样的事情:
// the outer component is a "container" for multiple stopwatches
tick: function() {
for (var i = 0; i < this.state.stopwatches.length; i++)
{
// if a particular stopwatch is "started", I'll increase it's time
if (this.state.stopwatches[i].status == "started")
{
this.state.stopwatches[i].time.seconds++;
// do some processing
}
}
// this is the suspicious code!
this.setState(this.state);
}
请注意,我正在更改 this.state 属性,然后在 state 对象本身上调用 setState()。这对我来说似乎很错误。但是,另一方面,为了不操纵 state 对象本身,我必须克隆它然后执行 setState(stateClone),但我不确定是否可以在 JS 中有效地克隆对象,如果我真的不应该这样做。
我可以继续做setState(this.state)吗?
【问题讨论】:
-
如果你在做你正在做的事情没有面临一些副作用,那么应该没问题。
-
实际上我在问从 ReactJS 的角度来看这是否是一个好习惯。也许有更好的方法。
标签: javascript reactjs