如何在React组件树外的非JSX文件中修改Redux的state
问题解答
1. 非组件文件修改Redux State可行性与报错修复
该操作完全可行,你遇到的dispatch is not a function报错根源是store导入路径错误:
- 你导出store的文件是
index.js,但Api脚本里导入的路径写的是./index.jsx,路径不匹配导致导入的store实际是undefined,调用方法自然报错。
修复步骤:
- 修正Api脚本的导入语句,将
import store from "./index.jsx"修改为import store from "./index.js",也可以省略后缀写为import store from "./index",前端打包工具会自动匹配js后缀的文件。 - 同时确认
actions.js中导出的foo是合法的Redux action创建函数,返回的对象必须包含type字段。
修复后的Api脚本示例:
// 修正导入路径 import store from "./index.js"; import foo from "./actions.js"; // 调用dispatch正常执行 store.dispatch(foo("Hello world!"));
2. Reducer返回undefined报错修复
该报错是因为你对应login字段的slice reducer没有遵循Redux的规范:所有执行路径下都不能返回undefined。
触发原因:
处理AUTH_SIGN_IN类型的action时,你的reducer没有返回任何值,或者缺少默认分支返回原state的逻辑。
修复步骤:
- 所有action处理分支都必须有明确返回值:如果需要修改state就返回新的state对象/数组,如果不需要修改就直接返回原state,禁止直接修改原state的属性。
- 必须给reducer加上
default分支,匹配不到对应action类型时直接返回原state。
正确的reducer写法示例:
// 初始化state也要定义,避免初始值为undefined const initialState = { userInfo: null, isLogin: false } const loginReducer = (state = initialState, action) => { switch(action.type) { case "AUTH_SIGN_IN": // 返回修改后的新state return { ...state, isLogin: true, userInfo: action.payload } // 其他action类型的处理逻辑... default: // 必须加默认分支返回原state return state } }
内容的提问来源于stack exchange,提问作者Alvin Cheng
相关产品推荐
相关产品推荐

