React Redux点击提交报错:dispatch is not a function 问题排查
问题根源分析
以下是导致dispatch is not a function报错的常见原因:
bindActionCreators未正确传入dispatch
如果你用bindActionCreators绑定setAlert到组件,必须传入从useDispatch获取的dispatch实例。错误写法会导致绑定后的action creator没有拿到dispatch:// 错误写法 const actions = bindActionCreators({ setAlert }, undefined);正确写法:
const dispatch = useDispatch(); const actions = bindActionCreators({ setAlert }, dispatch);组件未被Redux Provider包裹
Register组件必须放在Redux的Provider组件内部,否则useDispatch无法获取到store的dispatch方法。检查项目根组件结构,确保:<Provider store={store}> <Register /> </Provider>Action创建函数写法错误
若setAlert是同步action,必须返回标准的action对象(含type字段);若是异步action(使用thunk中间件),必须返回一个接收dispatch的函数:// 同步action正确写法 export const setAlert = (msg, alertType) => ({ type: 'SET_ALERT', payload: { msg, alertType } }); // 异步action正确写法(需配置thunk) export const setAlert = (msg, alertType) => dispatch => { dispatch({ type: 'SET_ALERT', payload: { msg, alertType } }); };直接调用Action创建函数而非通过dispatch触发
不能直接调用setAlert,必须通过dispatch触发action:// 错误写法 setAlert('注册失败', 'error'); // 正确写法 const dispatch = useDispatch(); dispatch(setAlert('注册失败', 'error'));
内容的提问来源于stack exchange,提问作者Rishabh Tanwar
相关产品推荐
相关产品推荐

