React Redux报错:无法读取undefined的'addition'属性,寻求解决方案
Redux计数器点击报错:Cannot read properties of undefined (reading 'addition') 的解决方法
问题场景
实现了基于Redux的递增/递减计数器按钮,点击按钮时触发错误:
Counter.js:11 Uncaught TypeError: Cannot read properties of undefined (reading 'addition')
错误原因
- actions导出错误:
store.js中错误地从store对象导出actions,Redux store本身没有actions属性,正确的actions是createSlice返回的切片对象的actions属性。 - reducer属性名错误:
subtractionreducer中操作了不存在的countReducer属性,对应初始状态的属性应为countNumber。 - Hook使用位置错误:
Counter.js中的useSelector和useDispatch未包裹在React组件函数内部,这两个Hook仅允许在组件或自定义Hook中调用。
修复后的代码
store.js
import { createSlice, configureStore } from '@reduxjs/toolkit'; const counterSlice = createSlice({ name: "counter", initialState: { countNumber: 0, countToggle: true, }, reducers: { addition(state) { state.countNumber++; }, subtraction(state) { // 修正属性名,替换不存在的countReducer为countNumber state.countNumber--; }, }, }); const store = configureStore({ reducer: counterSlice.reducer, }) // 修正actions导出路径,从store.actions改为counterSlice.actions export const storeAction = counterSlice.actions; export default store;
Counter.js
import { useDispatch, useSelector } from "react-redux"; import { storeAction } from "../redux-store/store"; import classes from './Counter.module.css'; // 将逻辑包裹在React组件函数内 const Counter = () => { const counter = useSelector((state) => state.countNumber); const dispatch = useDispatch(); const addHandler = () => { dispatch(storeAction.addition()); }; const subtractHandler = () => { dispatch(storeAction.subtraction()); }; return ( <div> <div className={classes.value}>{counter}</div> <button onClick={addHandler}>addition</button> <button onClick={subtractHandler}>subtraction</button> </div> ); }; export default Counter;
内容的提问来源于stack exchange,提问作者Mohit
相关产品推荐
相关产品推荐

