I'd like to add a new child key-value to an existing partent -happening on React. Let's say this is my state:
this.state = {
genres: {
Rock: '',
Jazz: '',
Pop: ''
}
}
And this is my method:
addingGenre(tw) {
this.setState({
genres: { [tw]: '', }
})
}
This is obviously not working, itoverwrites my full state --> {genres: tw}.
Thanks so much in advance :)
You need to push to the current state. So it should be something like this:
addingGenre(tw) {
this.setState({
genres: { ...this.state.genres, [tw: '']}
})
}
You can do it like this -
addingGenre(tw) {
const state = this.state;
state.genres[tw] = '';
this.setState(state)
}
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.