如何在Next.js+TypeScript中用useReducer更新嵌套对象状态?
替换嵌套对象状态的正确写法
你的问题出在reducer里对companyProfile的更新逻辑——你错误地把每个字段都赋值为整个payload对象,而不是直接用payload替换整个companyProfile。
修改后的Reducer代码
const Reducer = (state: initialStateAttributes, action: actionAttributes) => { switch(action.type) { case actionEnum.COMPANY_PROFILE_DATA: return { ...state, // 保留userInfo、isLoading等顶层状态不变 companyProfile: action.payload // 直接替换整个companyProfile对象 }; // 其他case逻辑... default: return state; // 必须保留default分支,避免状态丢失 } };
关键说明
- 直接替换而非逐个赋值:因为你需要完全覆盖
companyProfile的所有值,所以不需要用...state.companyProfile展开旧对象——这会保留旧字段,而我们要的是全量替换。 - 类型匹配检查:确保
axiosGetCompanyProfile类型和initialState里的companyProfile结构完全一致,TypeScript才不会报错。比如:type axiosGetCompanyProfile = { companyDescription?: string; companyLogo?: string; companyLogoPublicId?: string; companyName?: string; owner?: string; _id?: string; }; - 处理多余字段(可选):如果API返回的字段比
companyProfile定义的多,可以手动解构只保留需要的字段:case actionEnum.COMPANY_PROFILE_DATA: const { companyDescription, companyLogo, companyLogoPublicId, companyName, owner, _id } = action.payload; return { ...state, companyProfile: { companyDescription, companyLogo, companyLogoPublicId, companyName, owner, _id } };
这样修改后,dispatch action时,companyProfile就会被API返回的完整数据替换,而不是每个字段都赋值为整个payload对象。
内容的提问来源于stack exchange,提问作者kingNodejs
相关产品推荐
相关产品推荐

