How to update nested state properties in React(如何在 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 中更新嵌套状态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 React 中更新嵌套状态属性
				
        
 
            
        - 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
 - 从原点悬停时触发 translateY() 2022-01-01
 - 如何显示带有换行符的文本标签? 2022-01-01
 - 如何向 ipc 渲染器发送添加回调 2022-01-01
 - 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
 - 如何调试 CSS/Javascript 悬停问题 2022-01-01
 - 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
 - 为什么我的页面无法在 Github 上加载? 2022-01-01
 - 在不使用循环的情况下查找数字数组中的一项 2022-01-01
 - 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
 
						
						
						
						
						
				
				
				
				