What is the shortest way to modify immutable objects using spread and destructuring operators

前端 未结 6 1141
无人及你
无人及你 2021-01-30 22:34

I\'m looking for a pure function, to modify my immutable state object. The original state given as parameter must stay untouched. This is especially useful when working with fra

6条回答
  •  误落风尘
    2021-01-30 23:02

    Instead of writing boilerplate code (as answered above: (({[id]: deleted, ...state}) => state)(state)) which is hard to read, you could use some library to do the same:

    • https://github.com/cah4a/immutable-modify
    • https://github.com/kolodny/immutability-helper
    • https://github.com/M6Web/immutable-set
    • https://github.com/bormind/immutable-setter

    For example:

    import {remove} from 'immutable-modify'
    
    function updateState(state, item) {
       return remove(state, item.id)
    }
    

    It's also supports any nested updates:

    import {set} from 'immutable-modify'
    
    function updateState(state, item) {
       return set(state, 'user.products', (products) => ({
          ...products,
          items: products.items.concat(item),
          lastUpdate: Date.now()
       }))
    }
    

提交回复
热议问题