Updating the array object in React state using immutability helper

后端 未结 2 620
渐次进展
渐次进展 2020-12-25 14:11

I am updating an object within an array in React state using immutability helper.

The object I want to modify is nested:



        
相关标签:
2条回答
  • 2020-12-25 14:29

    One way to do it would be using $set

    let index = 0;
    let newState = update(this.state, {
       a: {
         b: {
          [index]: {
                   c: { $set: "new value"}
           }
        }
      }
    });
    this.setState(newState);
    

    jsfiddle

    0 讨论(0)
  • 2020-12-25 14:36

    Im importing update from immutability helper here :)

    this.state = {
      a: {
        b: [{ c: '', d: ''}, ...]
      }
    } 
    
    
    this.setState((prevState, props) => update(prevState, {
        a: {
            b: {
                $apply: b => b.map((item, ii) => {
                    if(ii !== n) return item;
                    return {
                        ...item,
                        c: 'new value'
                    }
                })
            }
        }
    }))
    
    0 讨论(0)
提交回复
热议问题