Storing an object in state of a React component?

后端 未结 6 1168
野趣味
野趣味 2020-12-07 16:05

Is it possible to store an object in the state of a React component? If yes, then how can we change the value of a key in that object using setState? I think it

6条回答
  •  被撕碎了的回忆
    2020-12-07 17:05

    In addition to kiran's post, there's the update helper (formerly a react addon). This can be installed with npm using npm install immutability-helper

    import update from 'immutability-helper';
    
    var abc = update(this.state.abc, {
       xyz: {$set: 'foo'}
    });
    
    this.setState({abc: abc});
    

    This creates a new object with the updated value, and other properties stay the same. This is more useful when you need to do things like push onto an array, and set some other value at the same time. Some people use it everywhere because it provides immutability.

    If you do this, you can have the following to make up for the performance of

    shouldComponentUpdate: function(nextProps, nextState){
       return this.state.abc !== nextState.abc; 
       // and compare any props that might cause an update
    }
    

提交回复
热议问题