164. 实现Immer的produce()

中等难度  -通过 / -执行

12. 实现 Immutability helper中, 我们实现了各种helper。

但是这些helper需要记住其使用方法,Immer 使用了另外一种方法,可以更加简单。

比如我们有如下state。

const state = [
  {
    name: 'BFE',
  },
  {
    name: '.',
  }
]

使用produce() 的话,可以按照意愿修改state。

const newState = produce(state, draft => {
  draft.push({name: 'dev'})
  draft[0].name = 'bigfrontend'
  draft[1].name = '.' // set为相同值。
})

注意,未变化的部分并没有拷贝。

expect(newState).not.toBe(state);
expect(newState).toEqual(
  [
    {
      name: 'bigfrontend',
    },
    {
      name: '.',
    },
    {
      name: 'dev'
    }
  ]
);
expect(newState[0]).not.toBe(state[0])
expect(newState[1]).toBe(state[1])
expect(newState[2]).not.toBe(state[2])

请实现你的produce().

  1. 目的并不是重写Immer,test case并不是要cover所有情况。
  2. 只需要实现简单对象和数组的基本使用方式,Map/Set和Auto freezing等不需要考虑。
  3. 需要保证未改变的数据部分不被拷贝。

注意特例。

(9)