我有这样的例子:
this.state = {
lang1: { name: 'Anglais', code: "en" },
lang2: { name: 'Français', code: "fr" }
};
我如何设置lang1.name的状态?当我这样做时,它不起作用:
this.setState({ lang1.name: "myExample" });
我是React Native的新人,我对此并不清楚
答案 0 :(得分:3)
this.setState({
lang1: {
name: "myExample",
code: this.state.lang1.code
}
});
答案 1 :(得分:3)
You can just do this. ... just adds exiting keys and then adds/overwrites new ones
this.setState({
lang1:{
...this.state.lang1,
name: "myExample"
}
})
答案 2 :(得分:2)
你可以这样做:
this.setState((previousState) => {
const lang1 = previousState.lang1
return {...lang1, name: 'myExample'}
})
答案 3 :(得分:0)
值是参数...
let data = this.state.objectState
data[prop] = value
this.setState({objectState: data})