React子组件重渲染后props部分丢失,求原因及更优解决方案
子组件props缺失、校验逻辑运行异常的根因与优化方案
问题基本情况
- 目前已有临时可用的实现方案,需要明确问题产生的根本原因,替换为更可靠的实现
- 向子组件传入共7个props:首次渲染时控制台可观测到全部props;第二次渲染时其中3个props丢失,直接访问这些缺失属性会触发“无法读取不存在属性”的模块报错
- 临时实现逻辑:嵌套校验props存在性、再校验
props.data存在性后才渲染卡片内容 - 异常观感:原本判断当
data类props缺失时,逻辑会直接返回空内容,但实际页面上的卡片字符能正常显示,和预期不符
当前临时实现代码
render() { /* 根据闪卡、测验场景的入参,动态切换卡片背景类 */ let bgColor = "card-body " if( this.props.outcome === null ){ /* 背景色保持默认中性状态 */ } else if ( this.props.outcome ) { /* 答对时的背景类 */ bgColor+= "bg-success " } else { /* 答错时的背景类 */ bgColor+= "bg-warning " }; log("Card has rendered"); console.log("props: ", this.props); // 直接执行以下代码会触发报错 // let data= this.props.data[0]; // console.log(data); return ( <> {this.props ? ( <> {this.props.data ? ( <> <div className="card text-center"> <div className={bgColor}> <h5 className="card-title">{this.props.data[this.props.cardIndex].character}</h5> <input onChange={this.handleOnChange} name="guessInput" type="text" value={this.props.guessInput} /> {/* {this.props.show ? ( <> </> ):( <> </> )} */} </div> </div> </> ):( <></> )} </> ):( <></> )} </> ); };
控制台观测日志
Card has rendered props: {guessInput: Array(0), data: Array(49), cardIndex: 0, translation: Array(49), handleChange: ƒ, …} cardIndex: 0 data: (49) [{…}, {…}, ...共49条条目] guessInput: [] handleChange: ƒ () outcome: null start: true translation: (49) [{…}, {…}, ...共49条条目] __proto__: Object Card has rendered props: {guessInput: Array(0), start: true, outcome: null, handleChange: ƒ} guessInput: [] handleChange: ƒ () outcome: null start: true __proto__: Object Review componentDidUpdate
问题根因拆解
- 无效判断问题:类组件的
this.props永远是非空对象,代码里第一层this.props ? (...)的判断永远成立,没有任何实际拦截作用 - 内容可正常显示的本质原因:两次打印的渲染日志来自两个独立的子组件实例,不是同一个组件的两次重渲染:
- 第一个实例接收了全部7个props,满足
this.props.data存在的判断条件,正常执行到渲染逻辑,读取对应卡片的字符并生成可见的DOM - 第二个实例只接收了4个props,其中
this.props.data为undefined,代码直接走三元判断的false分支,返回空片段,根本不会执行到读取this.props.data[...]的代码,因此不会触发属性报错
你看到的页面正常显示的内容,来自第一个带完整props的实例,并非props缺失的实例渲染生成,因此混淆了校验逻辑的实际运行效果
- 第一个实例接收了全部7个props,满足
- props缺失的原因:父组件在渲染第二个子组件实例时,没有透传
data/cardIndex/translation三个props,仅传入了其余四个属性
优化实现建议
- 删掉完全无效的
this.props ?判断,直接针对可空的嵌套属性做校验,消除冗余逻辑 - 补充数组越界校验,避免
cardIndex超过data数组长度时触发报错 - 用可选链语法替代多层嵌套三元判断,简化校验逻辑:
render() { let bgColor = "card-body "; // 背景色判断逻辑保持不变 if (this.props.outcome === null) { } else if (this.props.outcome) { bgColor += "bg-success "; } else { bgColor += "bg-warning "; } // 逐层校验取值,不满足条件直接返回空 const currentCard = this.props.data?.[this.props.cardIndex]; if (!currentCard) return null; return ( <div className="card text-center"> <div className={bgColor}> <h5 className="card-title">{currentCard.character}</h5> <input onChange={this.handleOnChange} name="guessInput" type="text" value={this.props.guessInput ?? ""} /> </div> </div> ); } - 排查父组件传参逻辑,定位第二个子组件实例的渲染分支,补上缺失的三个props,从根源避免props漏传的问题
内容的提问来源于stack exchange,提问作者Justin
相关产品推荐
相关产品推荐

