2016-10-11 68 views
1

当该值为对象时,如何更新反应状态对象内的值?例如:使用新的任意对象更新嵌套的反应状态对象

this.state = { nestedObj: { x: 0, y: 5 } }; 

在稍后的时间,我想更新nestedObj与基于从基于用户输入一个JSON.parse创建的对象上的任意对象。

我尝试以下方法,它不工作:

const newObj = {nestedObj: { x: 0, arbitraryKey: 'bla', anotherOne: { h: 0 }}}; 
this.setState(newObj); 

我真的想只是吹走任何对象驻留在this.state.nestedObj和替换它与任何对象在newObj定义。我怎样才能做到这一点?我在我的this.state中还有其他钥匙,所以如果这只会影响nestedObj,但我不会超级挑剔。 谢谢!

+0

做你试过'this.setState({nestedObj:newObj})'? –

回答

3

class Main extends React.Component { 
 
    constructor(props) { 
 
    super(props); 
 
    this.state = { 
 
     obj: {a: 'hello', b: 'world'} 
 
    }; 
 
    } 
 
\t 
 
    componentDidMount() { 
 
    console.log('obj is initialized to: ', this.state.obj); 
 
    } 
 
\t 
 
    handleClick =() => { 
 
\t const value = Math.random().toFixed(2); 
 
\t this.setState({ 
 
\t \t obj: {a: value, b: value} 
 
\t },() => console.log('obj is changed to: ', this.state.obj)); 
 
    }; 
 

 
    render() { 
 
\t return <button onClick={this.handleClick}>button</button> 
 
    } 
 
} 
 

 
ReactDOM.render(
 
\t <Main />, 
 
\t document.getElementById('root') 
 
);
<div id="root"></div> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

相关问题