如何在 React 中更新嵌套状态属性 [英] How to update nested state properties in React

查看:34
本文介绍了如何在 React 中更新嵌套状态属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用这样的嵌套属性来组织我的状态:

I'm trying to organize my state by using nested property like this:

this.state = {
   someProperty: {
      flag:true
   }
}

但是像这样更新状态,

this.setState({ someProperty.flag: false });

不起作用.如何正确地做到这一点?

doesn't work. How can this be done correctly?

推荐答案

为了 setState 嵌套对象,您可以按照以下方法操作,因为我认为 setState 不处理嵌套更新.

In order to setState for a nested object you can follow the below approach as I think setState doesn't handle nested updates.

var someProperty = {...this.state.someProperty}
someProperty.flag = true;
this.setState({someProperty})

这个想法是创建一个虚拟对象对其执行操作,然后用更新的对象替换组件的状态

The idea is to create a dummy object perform operations on it and then replace the component's state with the updated object

现在,展开运算符只创建对象的一层嵌套副本.如果您的状态高度嵌套,例如:

Now, the spread operator creates only one level nested copy of the object. If your state is highly nested like:

this.state = {
   someProperty: {
      someOtherProperty: {
          anotherProperty: {
             flag: true
          }
          ..
      }
      ...
   }
   ...
}

您可以在每个级别使用扩展运算符设置状态,例如

You could setState using spread operator at each level like

this.setState(prevState => ({
    ...prevState,
    someProperty: {
        ...prevState.someProperty,
        someOtherProperty: {
            ...prevState.someProperty.someOtherProperty, 
            anotherProperty: {
               ...prevState.someProperty.someOtherProperty.anotherProperty,
               flag: false
            }
        }
    }
}))

但是,随着状态变得越来越嵌套,上述语法变得越来越难看,因此我建议您使用 immutability-helper 包来更新状态.

However the above syntax get every ugly as the state becomes more and more nested and hence I recommend you to use immutability-helper package to update the state.

参见 this answer 关于如何使用 immutability-helper 更新状态.

See this answer on how to update state with immutability-helper.

这篇关于如何在 React 中更新嵌套状态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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