How can I update the state using this.setState
to set isPro
to true
?
this.state = {
userData: [{id: 1}, {username: 'John'}, {isPro: false}]
}
Judging by how your data is structured, you may update it like this:
this.setState(prev => ({
...prev,
userdata: [
...prev.userdata.filter(e => typeof e.isPro === 'undefined'),
{ isPro: true }
]
}));
But if I were you, I probably going to make a function to update the state in the component class:
updateUserData(data) {
this.setState(prev => {
// make a copy of the previous state
const copy = JSON.parse(JSON.stringify(prev));
// assign values
Object.entries(data).forEach(([k, v]) => {
// find the entries that have the same key from the object that passed in
const entries = copy.userdata.filter(entry => entry.hasOwnProperty(k));
// If the entries exist, update them
if(entries.length > 0) {
entries.forEach(d => (d[k] = v));
}
// otherwise, add a new entry
else {
copy.userdata.push({ [k]: v });
}
});
return copy;
});
}
And then update the data by calling:
this.updateUserData({ isPro: true, username: 'Bob' })
Then the state will be updated to
this.state = {
userData: [{ id: 1 }, { username: 'Bob' }, { isPro: true }]
}
You can make a copy of the array, then find the index where the dictionary you want to modify is, and then modify it:
UPDATE (sorry about misprints, fast writing...)
let userdatadummy = [...this.state.userData]
const k = userdatadummy.findIndex((item)=>Object.keys(item).includes('isPro'))
userdatadummy[k]['isPro']=true
this.setState({
userData: userdatadummy
})
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.