2016-10-11 73 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>