修改组件的状态然后调用“setState(this.state)”是一个好习惯吗?

2023-11-30

我正在使用 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属性,然后调用setState() on the state对象本身。这对我来说似乎很错误。但另一方面,为了not操纵state对象本身,我必须克隆它然后做setState(stateClone),但我不确定是否可以在 JS 中有效地克隆对象,也不确定我是否真的应该这样做。

我可以继续做吗setState(this.state) ?


而不是打电话this.setState(this.state)你可以打电话this.forceUpdate().

请记住,这不是推荐的更新组件状态的方法。如果您不确定自己的修改,请查看不变性助手.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

修改组件的状态然后调用“setState(this.state)”是一个好习惯吗? 的相关文章