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?
I'm not sure how to actually push my object onto the specified array in the setState function?
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:
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. ( MDN link )
I am not sure why you had added the comment //use setState to add a child
when the code snippet does not use hooks. I think hooks, or any other state management tool would be beneficial if the state object is so deeply nested.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.