使用createSlice时amount读取为undefined的问题排查
问题分析与解决
错误Cannot read properties of undefined (reading 'amount')的核心原因是:你的reducer中尝试读取payload.amount,但dispatch时传递的action未正确包含payload字段,导致payload为undefined,进而无法读取amount属性。
修复方案
有两种规范的修复方式,推荐使用第一种:
方式一:使用Redux Toolkit自动生成的Action Creators(推荐)
Redux Toolkit的createSlice已经为你生成了对应的action创建函数(deposit、withdrawal、transfer),直接调用这些函数可以避免手动构造action的格式错误。
- 在
Transactions.jsx中导入这些action创建函数:
import { deposit, withdrawal, transfer } from '../features/transactions/transactionsSlice';
- 修改
onTransaction函数的dispatch逻辑,根据按钮的action值匹配对应的action创建函数:
const onTransaction = (e) => { e.preventDefault(); const action = e.nativeEvent.submitter.name; const amount = +amountStr; // 根据按钮类型分发对应action switch(action) { case 'deposit': dispatch(deposit({ amount })); break; case 'withdraw': // 注意按钮name是withdraw,对应slice里的withdrawal action dispatch(withdrawal({ amount })); break; case 'transfer': dispatch(transfer({ amount })); break; default: break; } };
方式二:手动构造符合格式的Action
如果要手动编写action对象,必须将数据放在payload字段中,匹配reducer的读取逻辑:
const onTransaction = (e) => { e.preventDefault(); const action = e.nativeEvent.submitter.name; const amount = +amountStr; // 手动构造action时,将amount放入payload对象 const actionType = action === 'withdraw' ? 'withdrawal' : action; dispatch({ type: `transactions/${actionType}`, payload: { amount } }); };
原理说明
你的slice中所有reducer(比如deposit)都是从payload.amount读取数值的:
deposit: (state, { payload }) => { state.balance += payload.amount; // ... }
无论用哪种方式,只要确保dispatch的action包含payload字段,且payload内有amount属性,就能让reducer正确读取数值,解决报错。
内容的提问来源于stack exchange,提问作者antjuh
相关产品推荐
相关产品推荐

