简体   繁体   English

将一个元素插入另一个列表中的嵌套变量上的状态

[英]Insert an element to a list inside another on nested variables on state in react

I have a json of this type: 我有一个这种类型的json:

object:{

   object2:[
    {
      test:[
       {
       }
      ],
      name:''
    }
   ]

}

What I want to do is to set the state of a certain test element and what I did was this: 我想要做的是设置某个测试元素的状态,我做的是这样的:

this.setState(prevState => ({
        object: {
            ...prevState.object,
            object2: {
                ...prevState.object.object2[indexObject2],
                test: [
                    ...newTest
                ]
            }
        }
    }))

But when I do this the error this.state.object.object2.map is not a function occurs. 但是,当我这样做时,错误this.state.object.object2.map不是一个函数发生。 Thanks! 谢谢!

You can try 你可以试试

this.setState(prevState => ({
    object: {
        ...prevState.object,
        object2: {
            ...prevState.object.object2,
            {
                ...prevState.object.object2[indexObject2],
                test: [
                    ...newTest
                ]
            }                
        }
    }
}))

You are setting object2 as an Object , it should be an Array 您将object2设置为Object ,它应该是一个Array

object2: {
    ...prevState.object.object2[indexObject2],
    test: [
        ...newTest
    ]
}

Should be 应该

object2: [
    ...prevState.object.object2[indexObject2],
    test: [
        ...newTest
    ]
]

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

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