React+Redux开发Todo应用出现Cannot read property 'getState' of undefined报错
问题根因定位
控制台抛出Cannot read property 'getState' of undefined错误,核心原因是Redux Store 的导入导出语法不匹配:
- 在
/redux/store.js中,store实例是通过默认导出方式暴露的,对应代码为export default createStore(reducer) - 在
/index.js中,对store的引用使用了具名导入语法import { store } from "./redux/store" - 由于store模块没有暴露名为
store的具名导出值,最终导入得到的store为undefined。后续<Provider store={store}>将这个undefined值注入到应用上下文,Provider初始化时调用store.getState()就会触发属性读取报错。
修复方案
根据实际使用习惯选择任意一种修改方式即可解决问题:
- 方案1:调整
/index.js中的导入语法,匹配store模块的默认导出规则
将原有导入语句替换为不带花括号的默认导入写法:import store from "./redux/store"; - 方案2:调整
/redux/store.js中的导出语法,匹配已有的具名导入规则
将原有默认导出语句替换为具名导出写法:export const store = createStore(reducer);
完成修改后,Provider可以正常获取到完整的store实例,控制台报错会消失,Todo应用的添加、列表渲染功能可以正常运行。
内容的提问来源于stack exchange,提问作者16020278 Đỗ Đức Tâm
相关产品推荐
相关产品推荐

