foca icon indicating copy to clipboard operation
foca copied to clipboard

[Improvement] reset的特性无需深拷贝

Open SoonIter opened this issue 3 years ago • 2 comments

//defineModel.ts
  modelStore.appendReducer(
    uniqueName,
    createReducer({
      name: uniqueName,
---  initialState: parseState(initialStateStr),
+++ initialState: options.initialState,
      allowRefresh: !skipRefresh,
    }),
  );

js里没有完美的深拷贝,reset这个不太应该从拷贝的角度考虑🤔 我感觉有immer的存在,初始的options.initialState完全不会改变, 或许和pinia一样,改为函数,这样也不需要再存一份旧state了

state(){
   return {
       a:1,
       b:2
   }
}

SoonIter avatar Jul 25 '22 14:07 SoonIter

markdown格式可以再优化一下,

```diff
xxxxx
- aaaa
+ bbbb
yyyy

效果如下

xxxxx
- aaaa
+ bbbb
yyyy

modelStore.appendReducer 传入的initialState确实是不需要再重新拷贝了,因为有immer。但是如果开发者是主动调用则仍然需要。

const model = defineModel('test', {
  initialState,
  actions: {
    test(state) {
      return this.initialState;
    }
  }
});

因为开发者在actions中仍然可以调用到初始值,这时候没法限制修改intialState,除非我们对其使用Object.freeze,不过我想这算是一个Breaking Change

geekact avatar Jul 26 '22 10:07 geekact

不过我觉得可以在开发环境对initialState进行一个freeze操作,然后等到V2的时候再去掉环境判断

另一个思路是废弃this.initialState

geekact avatar Jul 26 '22 10:07 geekact

根据最新的逻辑,createReducer传入的initialState不再深拷贝,但是在开发环境下需要使用Object.freeze冻结。

geekact avatar Dec 14 '22 13:12 geekact