简体   繁体   English

如何在反应中设置对象的对象

[英]how to setState an object of an object in react

I'm hoping someone can give me some syntax/explanation help here i'm trying to call setState on an object nested in an object (data) in my state i'm a little stumped?我希望有人可以在这里给我一些语法/解释帮助我正在尝试对嵌套在我的状态中的对象(数据)中的对象调用 setState 我有点困惑?

I'm not sure how to actually push my object onto the specified array in the setState function?我不确定如何将我的对象实际推送到 setState 函数中的指定数组上?

Can someone help me out?有人可以帮我吗? Many thanks!非常感谢!

here is the state i'm working with:这是我正在使用的状态:

state={
    height: 50,
    parentCount: 1,
    data: 
      {
        parentId: 0,
        name: 'parent',
        children: [{name: 'Child One', distToWater: 0, children: [] }, {name: 'Child Two', distToWater: 0, children: [] }]
      },   
  }

Here's my function where I try to add a child to my children [] array that's nested inside my data object in state:这是我的函数,我尝试将一个孩子添加到我的 children [] 数组中,该数组嵌套在我的数据对象中:

addChild = () =>{

    for (let x in data.children ){
      for (child in x){
          let closest = 99999

          if(child.distToWater < closest){
              closest = child.distToWater
              var newBest = child 

              let newChild = { 
                name: 'child',
                distToWater: closest - 1,
                children: []
              }
          }


          this.setState({data.children[newBest]: [...newChild] }) //use setState to add a child object
      }
    }
  }

You can try something like this你可以试试这样的

  this.setState(prevState => ({
                    ...prevState,
                    data: {
                        ...prevState.data,
                        children: [...prevState.data.children, newBest]
                    }

                }))

Since it is nested deep inside, something like the following code snippet should do.由于它嵌套在内部深处,因此应该执行以下代码片段之类的操作。

const kid = { name: 'John', distToWater: 0, children: [] } // new object to add
const newChildren = [...this.state.data.children, kid]
const newData = { ...this.state.data, children: newChildren }
const newState = { ...this.state, data: newData }
this.setState(newState)

The above code snippet uses the spread operator.上面的代码片段使用了扩展运算符。 In case if you have not seen it before, it is a new JavaScript operator which would come very handy.如果你以前没有见过它,它是一个新的 JavaScript 运算符,会非常方便。 ( MDN link ) ( MDN 链接)

I am not sure why you had added the comment //use setState to add a child when the code snippet does not use hooks.当代码片段不使用钩子时,我不确定您为什么添加注释//use setState to add a child I think hooks, or any other state management tool would be beneficial if the state object is so deeply nested.我认为如果状态对象嵌套如此深,钩子或任何其他状态管理工具都会很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM