如何在Redux reducer中向嵌套状态数组添加payload传入的值?
问题原因
你收到"可能为null"的报错是因为初始状态里currentUser被定义为null,类型检查无法保证触发ADD_FOLLOW action时currentUser一定存在有效值,所以直接访问state.currentUser.follows会触发空值告警。
另外你目前的ADD_FOLLOW逻辑还有两个问题:
- 没有展开原有
currentUser的其他属性,直接赋值会导致uid、loggedIn、following等原有字段丢失 - 你需求是更新
following数组,但现有代码修改的是follows字段,和需求不符
解决方案
1. 修正ADD_FOLLOW分支逻辑
case actions.ADD_FOLLOW: { return { ...state, currentUser: { // 保留currentUser原有所有属性,避免字段丢失 ...state.currentUser, // 可选链+兜底空数组避免空值报错,按需求更新following数组 following: [ ...(state.currentUser?.following || []), action.payload.resource_id ] } } }
如果需要同步更新follows数组,按照同样的格式新增字段逻辑即可。
2. 从根源避免空值问题(可选)
可以调整初始状态结构,给currentUser设置默认空结构兜底,彻底避免currentUser为null的情况:
const initialState = { loggedIn: false, currentUser: { follows: [], following: [], uid: '' } }
内容的提问来源于stack exchange,提问作者Joel Hager
相关产品推荐
相关产品推荐

