reactjs - 注入 asyncReducers 时的 preloadedState
问题描述
怎么可能同时拥有 preloadedState(从服务器补水)和动态注入减速器?
在react-boilerplate
或如何在 Redux 应用程序中动态加载减速器以进行代码拆分?根据您正在查看的页面/组件,动态添加减速器的概念。摘自reducers.js
:
export default function createReducer(asyncReducers) {
return combineReducers({
users,
posts,
...asyncReducers
});
}
虽然这在从一个页面导航到另一个页面(或仅在客户端应用程序上)时效果很好;当从服务器补水数据时,我遇到了这个错误:
Unexpected property "comments" found in previous state received by the reducer. Expected to find one of the known reducer property names instead: "users", "posts". Unexpected properties will be ignored.
(comments
动态注入reducer的属性名在哪里)
这个错误的原因很清楚,因为preloadedState
来自服务器的(使用 React SSR)已经包含comments
并且初始 reducer 没有,因为这是之后动态添加的。如果我添加comments
到我的combineReducers
;错误就会消失 但这意味着在应用程序初始化时,我需要包含所有减速器;这并不理想。
解决方案
您应该能够使用虚拟减速器代替动态加载的减速器,动态加载的减速器将在加载真正的减速器时被替换。
{ comments: (state = null) => state }
这也可以自动完成,具体取决于您的实现,根据http://nicolasgallagher.com/redux-modules-and-code-splitting/
// Preserve initial state for not-yet-loaded reducers
const combine = (reducers) => {
const reducerNames = Object.keys(reducers);
Object.keys(initialState).forEach(item => {
if (reducerNames.indexOf(item) === -1) {
reducers[item] = (state = null) => state;
}
});
return combineReducers(reducers);
};
推荐阅读
- python - Python字典导致递归问题
- python - Python f-string 在浮点数上的惊人结果
- javascript - fetch 未被识别为异步函数
- python - Discord bot 未上线,可能是证书错误?
- python - 如何使用 Python 快速下载 Tar 文件、解压缩并将内容上传到 Azure 块存储?
- python - 只打开一个 Tk.Toplevel 窗口
- java - 在 Java 中,当我们在终端上打印字符串文字时,该字符串文字是否也存储在字符串池中?
- ffmpeg - FFmpeg 剪切视频结束没有声音
- python - 3D 底图 添加 3D 条形图
- python - sys.exit(0) 是在 python 中退出/杀死线程的有效方法吗?