How to update nested state properties in React

后端 未结 26 2027
野趣味
野趣味 2020-11-21 06:35

I\'m trying to organize my state by using nested property like this:

this.state = {
   someProperty: {
      flag:true
   }
}

But updating

相关标签:
26条回答
  • 2020-11-21 07:38

    There are many libraries to help with this. For example, using immutability-helper:

    import update from 'immutability-helper';
    
    const newState = update(this.state, {
      someProperty: {flag: {$set: false}},
    };
    this.setState(newState);
    

    Using lodash/fp set:

    import {set} from 'lodash/fp';
    
    const newState = set(["someProperty", "flag"], false, this.state);
    

    Using lodash/fp merge:

    import {merge} from 'lodash/fp';
    
    const newState = merge(this.state, {
      someProperty: {flag: false},
    });
    
    0 讨论(0)
  • 2020-11-21 07:38

    try this code:

    this.setState({ someProperty: {flag: false} });
    
    0 讨论(0)
提交回复
热议问题