React使用getDerivedStateFromProps触发却未更新state问题求助
问题解决
核心错误
你在getDerivedStateFromProps的状态更新逻辑中出现了取值路径错误:
你父组件传递的机构数据存储在名为institute的props对象下,判断分支中你正确读取了nextProps.institute.id做对比,但返回更新的state字段时,错误地直接从nextProps根级别读取id、name等属性,这些属性在props根级不存在,返回的值均为undefined,因此看起来state没有发生更新。
修正后代码
static getDerivedStateFromProps(nextProps, prevState) { // 新增可选链避免institute为undefined时报错 if (prevState.id !== nextProps.institute?.id) { return { id: nextProps.institute.id, name: nextProps.institute.name, contactName: nextProps.institute.contactName, phoneNumber: nextProps.institute.phoneNumber, city: nextProps.institute.city, street: nextProps.institute.street, number: nextProps.institute.number, deleted: nextProps.institute.deleted }; } console.log("null") return null; }
优化建议
如果上述字段在子组件内部不需要做修改操作,建议直接使用props渲染,无需同步到state,减少冗余状态避免出现数据不一致的问题。
内容的提问来源于stack exchange,提问作者Itzik.B
相关产品推荐
相关产品推荐

