React中useReducer执行后State变为undefined的问题排查
问题分析与修复
核心问题1:Reducer的Default分支未返回原State
你的sectionsReducer中,switch的default分支只有break,没有返回原state。当useReducer触发时(包括严格模式下的重复执行),如果没有匹配到任何case,会返回undefined,直接导致整个state被覆盖为undefined。
核心问题2:状态更新违反Immutable原则(潜在问题)
new_data函数中,虽然复制了state数组,但数组内的section对象仍是原引用,直接修改currentNewSection.data会污染原状态,可能引发不可预测的状态异常。
修复代码
1. 修复Reducer的Default分支
export default function sectionsReducer(state, action) { switch (action.type) { case "swap_sections": { return swap_sections( state, action.data.startIndex, action.data.destinationIndex ); } case "new_data": { return new_data(state, action.data.currentSectionId, action.data.newData); } case "swap_data": { return swap_data( state, action.data.currentSectionId, action.data.startIndex, action.data.destinationIndex ); } default: // 必须返回原state,防止状态丢失 return state; } }
2. 修复new_data函数的Immutable更新
function new_data(state, currentSectionId, newData) { // 先检查目标section是否存在,避免报错 const targetSection = findById(state, currentSectionId); if (!targetSection) return state; const keys = targetSection.data.map((data) => data.id); const id = keys.length > 0 ? Math.max(...keys) + 1 : 1; // 通过map创建新数组,替换目标section为新对象 return state.map(section => { if (section.id !== currentSectionId) return section; return { ...section, data: [...section.data, newData(id)] }; }); }
验证说明
- 修复Default分支后,无论是否触发匹配的
case,reducer都会返回有效状态,不会出现undefined的情况。 - 采用
map和对象展开的方式更新状态,严格遵循React的Immutable状态更新原则,避免原状态被污染。
内容的提问来源于stack exchange,提问作者Nyikus
相关产品推荐
相关产品推荐

