简体   繁体   中英

Using _.merge to update react state?

 this.state = {
   children: {
     1: {
       id:1,
       name: 'hello',
     }
   }
 }

I'm trying to update one of children by the following code

 // given a child

 var state = _.merge({}, state, {
   children: {
     [child.id]: child
   }
 })

This looks simple, but most SO posts recommend immutability helper so I'm wondering if there's any flaw with the above approach?

Note: This method mutates object.(Lodash documentation) ie I think you shouldn't use it to return a new state.

Use Object.assign method or {...object, newFieldValue} ES6 spread operator

试试这个

var state = Object.assign({}, state, { children: { [child.id]: child } })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM