2017-04-13 61 views
0

我要塑造我的終極版店裏像這樣並添加searchForm的多個同胞:終極版減速器嵌套Redux的存儲屬性

import { Map } from 'immutable' 

const searchForm = Map(
    { 
    'categories': ['meat'], 
    'mealTypes': [], 
    'location': { 
     place: {}, 
     distanceFromPlaceValue: 10, 
     distanceFromPlaceUnit: 'k' 
    }, 
    'keywords': '' 
    } 
) 

const initialState = Map(
    { 
    searchForm: searchForm 
    } 
) 

export default initialState 

到目前爲止,我已經減速了categories和searchForm的keywords和正在創建的存儲這樣的:

const reducer = combineReducers({ keywords, categories }) 
const store = createStore(
    reducer, 
    initialState, 
    devToolsEnhancer() 
) 

這給出了一個錯誤:

unexpected property "searchForm" found in previous state by the reducer...

CreateStore需要採用與redux商店的頂級屬性相匹配的reducer。有沒有辦法將商店嵌入商店中,並且無錯地傳遞給減速器?或者我是否需要更改我的redux商店的形狀,並將任何減速器設置爲頂級商店屬性?

回答

1

根據Redux的初始狀態DOC:

If you produced reducer with combineReducers, this must be a plain object with the same shape as the keys passed to it. Otherwise, you are free to pass anything that your reducer can understand.

您使用combineReducer與keywordcategories鍵,以便您的初始狀態,還必須包括這樣的密鑰,但在你的情況下,它僅包含searchForm關鍵。

你不需要改變你的狀態的形狀,你可以簡單地使用嵌套combineRedcuers

const reducer = combineReducers({searchForm: combineReducers({ keywords, categories })}); 

請注意,如果您使用的終極版combineReducers,狀態對象管理由該減速器必須是普通的對象(不可變對象)。 所以我建議是這樣的:

const searchForm = { 
    'categories': List(..), 
    'mealTypes': List(...), 
    'location': Map(...), 
    'keywords': '' 
} 

const initialState = { 
    searchForm: searchForm 
}; 

如果你想使用一成不變的對象作爲初始狀態,你可以使用Redux-Immutable它提供了使用Immutable.js API遍歷狀態combineReducers方法。請檢查此discussion瞭解更多詳情。

此外,無論您使用Redux還是Redux-Imuable狀態對象(普通或不可變),屬性都必須對應傳遞給combineReducers的對象的鍵。

+0

感謝這工作。我剛剛意識到我已經在使用'redux-immutable'中的'import {combineReducers} – user2602079

相關問題