React useState更新对象报错:()=>void无法赋值给SetStateAction类型
解决React函数式更新状态时的TypeScript报错问题
问题根源
你遇到的TypeScript错误是因为setCustomerResponse的函数式更新回调没有返回新的状态对象,且直接修改了传入的prevCustomerResponse(违反React状态不可变原则),导致回调返回void,不符合SetStateAction要求的返回类型。
修复方案
方案1:直接传入新状态对象(不需要依赖旧状态时)
如果接口返回的值是完整覆盖现有状态,不需要保留旧状态的其他属性,直接构造新对象传入:
setCustomerResponse({ firstName: response.party.person.personNameList[0].firstName, lastName: response.party.person.personNameList[0].lastName, currentPremiumDue: response.policyDetail.currentPremiumDue });
方案2:函数式更新并返回新对象(需要依赖旧状态时)
如果需要保留旧状态中的其他属性(比如后续扩展状态字段),必须通过解构旧对象生成新对象,不能直接修改旧状态:
setCustomerResponse((prevCustomerResponse) => ({ ...prevCustomerResponse, // 保留旧状态的所有属性 firstName: response.party.person.personNameList[0].firstName, lastName: response.party.person.personNameList[0].lastName, currentPremiumDue: response.policyDetail.currentPremiumDue }));
额外注意事项
为避免运行时出现Cannot read property 'xxx' of undefined错误,建议给嵌套属性加上可选链检查:
firstName: response.party?.person?.personNameList?.[0]?.firstName || "", lastName: response.party?.person?.personNameList?.[0]?.lastName || "", currentPremiumDue: response.policyDetail?.currentPremiumDue || ""
内容的提问来源于stack exchange,提问作者apex2022
相关产品推荐
相关产品推荐

