[英]How to add new child key-value to a React State object
I'd like to add a new child key-value to an existing partent -happening on React.我想向 React 上发生的现有 partent 添加一个新的 child 键值。 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}.这显然不起作用,它覆盖了我的完整状态 --> {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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.