React类组件无法正常接收props、本地state不更新问题排查
问题原因
- 上层组件初始值错误:你定义
institute状态时初始值设为了空数组[],但后续逻辑中你将institute作为对象使用,读取它的object、errorName属性。空数组的object属性值为undefined,而你判断渲染InstituteForm的条件是institute.object !== null,undefined !== null的结果为true,所以接口请求还没返回时,InstituteForm组件就被提前渲染了,此时传入的instituteprop值为undefined。 - 类组件状态未同步props更新:类组件的本地state只会在组件首次初始化的时候从props取值一次,后续上层组件接口请求完成更新props时,你没有在
InstituteForm中监听props变化更新本地state,所以state一直停留在初始的空值状态。 - 热重载生效的原因:热重载会销毁原有组件重新初始化,此时接口请求已经完成,props已经有有效值,组件初始化state时就能拿到正确的值,所以看起来就正常了。
修复方案
方案1(更推荐,从根源避免提前渲染)
修改上层组件EditInstitute的状态初始值,和接口返回的结构对齐:
// 把原来的 useState([]) 改成如下 const [institute, setInstitute] = useState({object: null})
修改后初始状态下institute.object为null,会命中Alert的渲染逻辑,不会提前渲染InstituteForm,等接口请求完成更新institute之后,object有有效值才会渲染表单组件,此时表单初始化时props就有正确值,不用额外做同步逻辑。
方案2(如果需要保留现有渲染逻辑,增加props同步能力)
在InstituteForm类组件中增加componentDidUpdate生命周期,监听institute prop的变化,同步更新本地state:
class InstituteForm extends React.Component { state = { id: (this.props.institute ? this.props.institute.id : ''), name: (this.props.institute ? this.props.institute.name : ''), contactName: (this.props.institute ? this.props.institute.contactName : ''), phoneNumber: (this.props.institute ? this.props.institute.phoneNumber : ''), city: (this.props.institute ? this.props.institute.city : ''), street: (this.props.institute ? this.props.institute.street : ''), number: (this.props.institute ? this.props.institute.number : ''), deleted: (this.props.institute ? this.props.institute.deleted : ''), } // 新增以下生命周期代码 componentDidUpdate(prevProps) { // 只有当institute prop发生变化且有有效值时才更新state if (this.props.institute && this.props.institute !== prevProps.institute) { this.setState({ id: this.props.institute.id, name: this.props.institute.name, contactName: this.props.institute.contactName, phoneNumber: this.props.institute.phoneNumber, city: this.props.institute.city, street: this.props.institute.street, number: this.props.institute.number, deleted: this.props.institute.deleted, }) } } // 原有render代码不变 render() { // ...原有逻辑 } }
内容的提问来源于stack exchange,提问作者Itzik.B
相关产品推荐
相关产品推荐

