修改组件的状态然后调用“setState(this.state)”是一个好习惯吗? [英] Is it a good practice to modify a component's state and then call "setState(this.state)"?

查看:135
本文介绍了修改组件的状态然后调用“setState(this.state)”是一个好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ReactJS。

I'm using ReactJS.

我有一个statefull组件(秒表容器)和多个子组件,它们是无状态的(秒表)。

I have a statefull component (stopwatch container) and multiple child components which are stateless (stopwatches).

在外部组件中,我做的是这样的事情:

In the outer component, I'm doing something like this:

// 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()。这对我来说似乎是错的。但是,另一方面,为了操纵状态对象本身,我必须克隆它,然后执行 setState(stateClone),但我不确定是否可以在JS中有效地克隆对象,如果我真的应该这样做的话。

Notice that I'm changing the this.state property and then calling setState() on the state object itself. This seems so wrong to me. But, in the other hand, in order to not manipulate the state object itself, i'd have to clone it and then do setState(stateClone), but I'm not sure if it's possible to clone objects effectively in JS, neither if I really should do this.

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

推荐答案

您可以只调用 this.setState(this.state) /component-api.html#forceupdaterel =nofollow> this.forceUpdate()

Instead of calling this.setState(this.state) you can just call this.forceUpdate().

请记住,这不是推荐更新组件状态的方法。如果您不确定您的修改,请查看 Immutability Helpers

Just remember that this is not recommended way of updating components state. If you are unsure about your modifications take a look on Immutability Helpers.

这篇关于修改组件的状态然后调用“setState(this.state)”是一个好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆