我有一个 React 应用程序,它动态加载模块,包括模块的减速器函数,然后调用 Redux 的replaceReducer 来替换减速器。不幸的是我收到了一个错误
在传递给 createStore 的初始状态参数中发现意外的键“bookEntry”。期望找到已知的减速器键之一:“bookList”、“root”。意外的键将被忽略。
书名在哪里was正在更换的旧减速机上的钥匙。从 bookEntry 模块开始并切换到 bookList 会导致此逆错误
在传递给 createStore 的初始状态参数中发现意外的键“bookList”。期望找到已知的减速器键之一:“bookEntry”、“root”。意外的键将被忽略。
代码如下 - 取消注释注释的代码实际上可以解决此问题,但我猜应该不需要它。
我是否对 Redux 做了其他错误,使得这段代码变得必要?
function getNewReducer(reducerObj){
if (!reducerObj) return Redux.combineReducers({ root: rootReducer });
//store.replaceReducer(function(){
// return {
// root: rootReducer()
// }
//});
store.replaceReducer(Redux.combineReducers({
[reducerObj.name]: reducerObj.reducer,
root: rootReducer
}));
}
一般来说we don’t建议您在更改路线或加载新模块时“清理”数据。这使得应用程序变得不太可预测。如果我们谈论的是数十万记录,那么当然。这是您计划加载的数据量吗?
如果每个页面上只有几千个项目,则卸载它们没有任何好处,并且会因添加到应用程序的复杂性而产生负面影响。因此,请确保您正在解决真正的问题,而不是过早优化。
现在,来看警告消息。检查定义在里面combineReducers()
。这意味着意外的状态键将被丢弃。删除后bookEntry
管理的减速器state.bookEntry
,这部分状态不再被新的根减速器识别,并且combineReducers()
记录了它将被丢弃的警告。请注意,这是警告,而不是错误。你的代码运行得很好。我们用console.error()
使警告突出,但它实际上并没有抛出,所以你可以安全地忽略它。
我们真的不想让警告可配置,因为你本质上是隐式删除部分应用程序状态。通常人们这样做是错误的,而不是故意的。所以我们想对此发出警告。如果您想绕过警告,最好的选择是编写根减速器(当前由combineReducers()
) 用手。它看起来像这样:
// I renamed what you called "root" reducer
// to "main" reducer because the root reducer
// is the combined one.
let mainReducer = (state, action) => ...
// This is like your own combineReducers() with custom behavior
function getRootReducer(dynamicReducer) {
// Creates a reducer from the main and a dynamic reducer
return function (state, action) {
// Calculate main state
let nextState = {
main: mainReducer(state.main, action)
};
// If specified, calculate dynamic reducer state
if (dynamicReducer) {
nextState[dynamicReducer.name] = dynamicReducer.reducer(
nextState[dynamicReducer.name],
action
);
}
return nextState;
};
}
// Create the store without a dynamic reducer
export function createStoreWithoutDynamicReducer() {
return Redux.createStore(getRootReducer());
}
// Later call this to replace the dynamic reducer on a store instance
export function setDynamicReducer(store, dynamicReducer) {
store.replaceReducer(getRootReducer(dynamicReducer));
}
然而,我们推荐的模式是保留旧减速机 https://stackoverflow.com/questions/32968016/how-to-dynamically-load-reducers-for-code-splitting-in-a-redux-application.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)