redux,版本控制预加载状态?

问题描述 投票:0回答:1

http://redux.js.org/docs/api/createStore.html

[preloadedState](任意):初始状态。您可以选择指定 它可以在通用应用程序中从服务器获取状态,或者 恢复之前序列化的用户会话。

我可以使用 preloadedState 参数成功初始化存储。

但是有时我需要改变状态的结构。

举个例子,我最初有

{
  totalCount: 3,
  usedCount: 1
}

现在我想把它改成

{ 
  totalCount: 3,
  unusedCount: 2
}

那么第一个结构中存储的状态现在将不再有效。
至少我想放弃旧的状态并从新的初始状态重新开始。

我将状态存储在服务器中并将其用作 preloadedState 参数。
有没有办法在状态结构发生变化时丢弃服务器存储的状态?

redux
1个回答
0
投票

我正在分享我的解决方案。 我创建了 HOC 减速器 (http://redux.js.org/docs/recipes/reducers/ReusingReducerLogic.html)

 export function versionedReducer(reducerFunction) {

   return (state, action) => {

     const isInitializationCall = state === undefined

     if (isInitializationCall) {
       return state
     }

     const { version } = reducerFunction(undefined, {type: undefined})
     if (!version) {
       throw "should versioned"
     }
     const shouldAcceptPreloadedState = state.version && state.version >= version

     if (!shouldAcceptPreloadedState) {
       state = undefined
     }

     return reducerFunction(state, action)

   }
 }
© www.soinside.com 2019 - 2024. All rights reserved.