我想像这样塑造我的 redux 存储并添加更多的 searchForm 兄弟:
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
到目前为止,我已经为 searchForm 的 categories
和 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 。有没有办法嵌套商店,就像我所做的那样,并在没有错误的情况下传递 reducer ?或者我是否需要更改 redux 存储的形状并让任何 reducer 成为顶级存储属性?
最佳答案
根据 Redux 初始状态文档:
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与keyword
和categories
键一起使用,因此您的初始状态也必须包含此类键,但在您的情况下,它仅包含searchForm
key 。
您不需要更改状态的形状,只需使用嵌套的combineRedcuers
:
const reducer = combineReducers({searchForm: combineReducers({ keywords, categories })});
请注意,如果您使用 Redux combineReducers
,则此 reducer 管理的状态对象必须是普通对象(而不是不可变对象(immutable对象))。
所以我建议这样:
const searchForm = {
'categories': List(..),
'mealTypes': List(...),
'location': Map(...),
'keywords': ''
}
const initialState = {
searchForm: searchForm
};
如果你想使用不可变对象(immutable对象)作为初始状态,你可以使用 Redux-Immutable它提供了使用 Immutable.js API 来迭代状态的 combineReducers
方法。请检查这个discussion了解更多详情。
此外,无论您使用 Redux 还是 Redux-Imuable 状态对象(plain 或 Immutable)属性都必须与传递给 combineReducers
的对象键相对应。
关于javascript - 用于嵌套 Redux 存储属性的 Redux reducer ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43387160/