我正在做一个关于 react/redux 的研究项目。写了两个reducer:
const currentInputDataReducer = (state = defaultState, action) => {
switch (action.type) {
....
default: {
return state;
}
}
};
const expensesIncomeListReducer = (state = defaultState, action) => {
switch (action.type) {
....
default: {
return state;
}
}
};
对于视图状态:
const defaultState = {
calcState: {
currentInputData: {
currentDate: '',
currentMoney: '',
},
expensesIncomeList: [],
},
};
现在我想组合它们并导出它们:
export default combineReducers({
currentInputDataReducer,
expensesIncomeListReducer,
});
在索引文件中创建存储库:
const store = createStore(rootReducer);
在我使用连接的组件中:
export default connect(mapStateToProps, actionCreators)(FormPanel);
结果,出现错误:
The above error occurred in the <ConnectFunction> component:
in ConnectFunction (created by Calc)
in div (created by Calc)
in Calc (created by Context.Consumer)
in Route (created by App)
in Switch (created by App)
in div (created by App)
in div (created by App)
in div (created by App)
in div (created by App)
in App
in Router (created by BrowserRouter)
in BrowserRouter
in Provider
为什么会发生这种情况?这在我将一个 reducer 一分为二并应用 combineReducers 函数后开始出现。
当 reducer 组合在一起时,主状态变成了一个对象,其中包含这些 reducer 的状态值。
调用时
状态将如下所示:
在将状态划分为多个 reducer 时,您需要在所有使用此状态的对象中考虑到这一点。在您的情况下,状态对象很可能不再可以通过
state.someObject
它现在应该是的旧类型名称访问,state.currentInputDataReducer.someObject
或者state.expensesIncomeListReducer.someObject
取决于它在拆分后的确切位置。你
defaultState
的需要分成两个——每个减速器都有自己的。组合reducer时可以设置状态名称: