You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.memo自定义比较函数未被调用、组件不更新如何解决?

问题核心原因

  • 第一个也是最直接的原因:你自定义的比较函数areMatchesEqual定义顺序错误
    你使用const声明该函数,且写在了memo()调用的后面。const声明的变量存在暂存死区,执行memo()的时候areMatchesEqual还未完成初始化,值为undefined,React会直接使用默认的浅比较逻辑,你的自定义函数从未被调用,所以不会有打印输出。
  • 第二个问题:比较函数内的属性名和实际传入的prop不匹配
    你给组件传的属性是item={item},但你在比较函数里写的是prevProps.match,该属性根本不存在,就算函数能正常执行,比较逻辑也会出错。
  • 补充:你最初不传额外int属性时组件不更新,是因为item对象的引用没有发生变化,默认浅比较判定props无变化,所以不会触发重渲染。

解决方法

  1. 调整自定义比较函数的顺序,将它移动到memo()调用之前
  2. 修正比较函数内的属性名,将match替换为实际传入的item
  3. 如果你的修改是直接更改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 07:36:05