React.memo自定义比较函数未被调用、组件不更新如何解决?
问题核心原因
- 第一个也是最直接的原因:你自定义的比较函数
areMatchesEqual定义顺序错误
你使用const声明该函数,且写在了memo()调用的后面。const声明的变量存在暂存死区,执行memo()的时候areMatchesEqual还未完成初始化,值为undefined,React会直接使用默认的浅比较逻辑,你的自定义函数从未被调用,所以不会有打印输出。 - 第二个问题:比较函数内的属性名和实际传入的prop不匹配
你给组件传的属性是item={item},但你在比较函数里写的是prevProps.match,该属性根本不存在,就算函数能正常执行,比较逻辑也会出错。 - 补充:你最初不传额外int属性时组件不更新,是因为
item对象的引用没有发生变化,默认浅比较判定props无变化,所以不会触发重渲染。
解决方法
- 调整自定义比较函数的顺序,将它移动到
memo()调用之前 - 修正比较函数内的属性名,将
match替换为实际传入的item - 如果你的修改是直接更改
item内部的属性而没有更新item的引用,自定义比较函数里直接比较对应内部属性即可。
修正后的代码示例:
// 先定义比较函数 const areMatchesEqual = (prevProps, nextProps) => { console.log('waat'); return ( prevProps.item.MatchWinnerPrediction === nextProps.item.MatchWinnerPrediction && prevProps.item.HomeGoalsPrediction === nextProps.item.HomeGoalsPrediction && prevProps.item.AwayGoalsPrediction === nextProps.item.AwayGoalsPrediction ); }; // 再调用memo包裹组件 export const RenderMatchItem = memo((props) => { const { week, item, setPrediction, reRenderStateForWeekCallback } = props; return ( <View style={appStyles.matchContainer}> <RenderMatchText item={item} /> <RenderBottomRow week={week} match={item} setPrediction={setPrediction} reRenderStateForWeekCallback={reRenderStateForWeekCallback} /> </View> ); }, areMatchesEqual);
内容的提问来源于stack exchange,提问作者TruffelNL
相关产品推荐
相关产品推荐

