Reactjs 使用新的任意对象更新嵌套的反应状态对象
当react state对象中的值是对象时,如何更新该值?例如:Reactjs 使用新的任意对象更新嵌套的反应状态对象,reactjs,Reactjs,当react state对象中的值是对象时,如何更新该值?例如: this.state = { nestedObj: { x: 0, y: 5 } }; 稍后,我想使用基于用户输入的JSON.parse创建的对象的任意对象更新该nestedObj 我尝试了以下方法,但不起作用: const newObj = {nestedObj: { x: 0, arbitraryKey: 'bla', anotherOne: { h: 0 }}}; this.setState(newObj); 我真的很想
this.state = { nestedObj: { x: 0, y: 5 } };
稍后,我想使用基于用户输入的JSON.parse
创建的对象的任意对象更新该nestedObj
我尝试了以下方法,但不起作用:
const newObj = {nestedObj: { x: 0, arbitraryKey: 'bla', anotherOne: { h: 0 }}};
this.setState(newObj);
我真的很想把驻留在this.state.nestedObj的任何对象吹走,并用newObj
中定义的任何对象替换它。我该怎么做?我的this.state中有其他键,因此如果这只影响nestedObj
就很理想了,但我不是特别挑剔。
谢谢
类主扩展React.Component{
建造师(道具){
超级(道具);
此.state={
obj:{a:你好,b:世界}
};
}
componentDidMount(){
log('obj被初始化为:',this.state.obj);
}
handleClick=()=>{
常量值=Math.random().toFixed(2);
这是我的国家({
对象:{a:value,b:value}
},()=>console.log('obj改为:',this.state.obj));
};
render(){
返回按钮
}
}
ReactDOM.render(
,
document.getElementById('root'))
);代码>
您是否尝试过此.setState({nestedObj:newObj})
?