How to update nested state properties in React

后端 未结 26 1986
野趣味
野趣味 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:19

    I take very seriously the concerns already voiced around creating a complete copy of your component state. With that said, I would strongly suggest Immer.

    import produce from 'immer';
    
     produce(this.state, s => { s.form.username = e.target.value }) } />
    

    This should work for React.PureComponent (i.e. shallow state comparisons by React) as Immer cleverly uses a proxy object to efficiently copy an arbitrarily deep state tree. Immer is also more typesafe compared to libraries like Immutability Helper, and is ideal for Javascript and Typescript users alike.


    Typescript utility function

    function setStateDeep(comp: React.Component, fn: (s: 
    Draft>) => any) {
      comp.setState(produce(comp.state, s => { fn(s); }))
    }
    
    onChange={e => setStateDeep(this, s => s.form.username = e.target.value)}
    

提交回复
热议问题