2017-04-15 50 views
0

http://redux.js.org/docs/api/createStore.htmlredux,版本預載狀態?

[preloadedState](任意):初始狀態。您可以選擇指定 它來保護通用應用程序中的服務器狀態,或者恢復先前序列化的用戶會話。

我可以使用preloadedState參數成功初始化存儲。

但是有時我需要改變狀態的結構。

舉個例子,我最初有

{ 
    totalCount: 3, 
    usedCount: 1 
} 

現在我想將其更改爲

{ 
    totalCount: 3, 
    unusedCount: 2 
} 

然後存儲的狀態在第一結構現在是無效的。
至少我想放棄舊的狀態,並從新的初始狀態重新開始。

我在服務器中存儲狀態並將其用作preloadedState參數。
有沒有辦法在狀態結構更改時放棄服務器存儲狀態?

回答

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) 

    } 
}