Reputation: 6431
In react native, when I wish to update the value of one item in the state dictionary, this is how I do it:
this.setState({
showFullImage: true,
})
but some developers in my team add ...this.state
like this:
this.setState({
...this.state,
showFullImage: true,
})
To me this is wrong since it will update everything reliant on state. Including anything that may not need updating. My approach (first one) has been working all along, and does not remove all other values from state... Am I wrong in this?
Upvotes: 0
Views: 124
Reputation: 3141
setState
method update state value for provided key. It only update selected keys. So if you want to update single property of state you can directly update.
If you want to update single property of child level than you need ...
For example.
this.state = {
showImage: true,
user: {
name: 'test',
age: 10
}
}
updateName(name) {
const { user } = this.state
this.setState({
user: {
...user,
name
}
})
}
toggleImage() {
const { showImage } = this.state
this.setState({
showImage: !showImage
})
}
Upvotes: 0
Reputation: 6379
You are right, there is no need to spread out the parts of the state you are not updating. Only update what needs to be updated.
Upvotes: 1