3 回答
![?](http://img1.sycdn.imooc.com/533e4cde000148e602000200-100-100.jpg)
TA贡献1895条经验 获得超7个赞
您需要创建原始对象的副本,并且只更改要更新的属性。最简单的方法是使用对象扩展运算符:
this.setState(currentState => ({enabled: {...currentState.enabled, one: true}}));
或更详细的形式:
this.setState(currentState => {
const enabled = {...currentState.enabled, one: true};
return {enabled};
});
如果属性名称仅在运行时已知,您可以这样做:
const setEnabled = name => {
this.setState(currentState => ({enabled: {...currentState.enabled, [name]: true}}));
};
![?](http://img1.sycdn.imooc.com/5333a1a90001c8d802000200-100-100.jpg)
TA贡献1785条经验 获得超8个赞
您可以在对象的键周围使用大括号来使用变量来确定键
const dynamicKey = 'one';
const newObj = {[dynamicKey]: true} //equals {one: true}
由于 this.setState 仅在顶级键上合并,因此您必须创建当前启用对象的副本并使用大括号表示法:
let dynamicProperty = "one"
this.setState({
enabled: {...this.state.enabled, [dynamicProperty]: true}
})
添加回答
举报