Redux Toolkit中TypeError: Dispatch Action非函数问题求助
Redux Toolkit报错
TypeError: counterActions.increment is not a function的解决方法 错误根源
问题出在Counter Slice的导出语句上:在counterSlice.js中,你错误地将counterSlice.reducer赋值给了counterActions,但Redux Toolkit的createSlice返回对象里,actions属性才包含自动生成的action创建函数(比如increment、decrement),reducer只是该切片的状态处理函数。
修复步骤
修改counterSlice.js的最后一行代码:
原错误代码:
module.exports.counterActions = counterSlice.reducer;
改为:
module.exports.counterActions = counterSlice.actions;
修复后的完整Counter Slice代码
const { createSlice } = require("@reduxjs/toolkit"); const initialState = { count: 0, }; const counterSlice = createSlice({ name: "counter", initialState, reducers: { increment: (state, action) => state.count++, decrement: (state, action) => state.count--, }, }); module.exports = counterSlice.reducer; module.exports.counterActions = counterSlice.actions; // 修复后的导出语句
验证结果
你的Store配置和调度代码逻辑没有问题,修复上述导出错误后,重新运行代码即可正常触发action,控制台会输出状态变化:
{ counter: { count: 0 } } { counter: { count: 1 } } { counter: { count: 0 } }
内容的提问来源于stack exchange,提问作者Imdadul Haque
相关产品推荐
相关产品推荐

