React-Redux计数器报错:_store_index_js__WEBPACK_IMPORTED_MODULE_2__.default.increment不是函数
Redux计数器报错问题排查
我是Redux新手,正在尝试用Redux实现计数器功能,但点击Increment/Decrement按钮时触发如下报错:
Uncaught TypeError: _store_index_js__WEBPACK_IMPORTED_MODULE_2__.default.increment is not a function at increment (App.js:10:1) at HTMLUnknownElement.callCallback (react-dom.development.js:4164:1) at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:1) at invokeGuardedCallback (react-dom.development.js:4277:1) at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:4291:1) at executeDispatch (react-dom.development.js:9041:1) at processDispatchQueueItemsInOrder (react-dom.development.js:9073:1) at processDispatchQueue (react-dom.development.js:9086:1) at dispatchEventsForPlugins (react-dom.development.js:9097:1) at react-dom.development.js:9288:1
计数器数值状态未发生变化。相关代码如下:
App.js
import { useSelector, useDispatch } from 'react-redux'; import './App.css'; import actions from './store/index.js'; function App() { const counter = useSelector((state) => state.counter); const dispatch = useDispatch(); const increment = ()=> { dispatch(actions.increment()); } const decrement = () => { dispatch(actions.decrement()); } const addBy = () => { dispatch(actions.addBy(10)) } return ( <div> <h1>Counter App</h1> <h2>{counter}</h2> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> <button onClick={addBy}>Add By 10</button> </div> ); }
index.js
import { configureStore, createSlice } from '@reduxjs/toolkit'; const counterSlice = createSlice({ name: 'counter', initialState : { counter: 0 }, reducers: { increment(state, action) { state.counter++; }, decrement(state, action) { state.counter--; }, addBy(state, action) { state.counter += action.payload; } } }) export const actions = counterSlice.actions; const store = configureStore({ reducer: counterSlice.reducer }) export default store;
问题原因与解决方法
问题出在actions的导入方式错误:
你在index.js里用export const actions做了命名导出,但在App.js里却用import actions from './store/index.js'做了默认导入。默认导入拿到的是index.js里的默认导出(也就是store实例),而不是你定义的actions对象,自然找不到increment方法。
修复方案:
把App.js中的导入语句修改为命名导入:
import { actions } from './store/index.js';
或者更简洁的方式,直接导入需要的action创建函数:
import { increment, decrement, addBy } from './store/index.js';
此时调用dispatch可以直接写:
const increment = ()=> { dispatch(increment()); } const decrement = () => { dispatch(decrement()); } const addBy = () => { dispatch(addBy(10)) }
这样就能正确触发action,更新计数器状态了。
内容的提问来源于stack exchange,提问作者coding beast
相关产品推荐
相关产品推荐

