【问题标题】:React.memo re-renders recursive components without running the areEqual functionReact.memo 重新渲染递归组件而不运行 areEqual 函数
【发布时间】:2021-06-17 15:51:03
【问题描述】:

我有一个带有 cmets 的页面。一个注释可以包含一个子字段,它是一个 cmets 数组。 我有一个组件 CommentGroup,它呈现一个 CommentCard,如果找到字段 children,另一个 CommentGroup 与孩子一起呈现。 这就是它的样子:

<div className={styles.commentsWrapperElements}>
  <div className={styles.commentsWrapperElementsParent}>
      <CommentCard
          comment={comment}
          key={comment.id}
          collapsed={collapsed}
          onReplyClick={onReplyClick}
          onDeleteClick={onDeleteClick}
          repliedTo={replyToId === comment.id}
          order={order}
      />
  </div>
  {comment?.children?.length > 0 ?
      <div className={styles.commentsWrapperElementsChildren}>
          {comment.children.map(e => <CommentCardGroup
              comment={e}
              replyToId={replyToId}
              onDeleteClick={onDeleteClick}
              onReplyClick={onReplyClick}
              key={e.id}
              addComment={addComment}
              order={order}
          />)}
      </div> : <></>
  }
</div>

我在这个带有自定义函数的组件上使用了 React.memo,它适用于顶级组件,但不适用于子组件(嵌套组件)。我用这个函数调试:

export function areEqual(prevProps, nextProps) {
    console.log('-');
    return false;
}

日志的数量等于父元素的数量,即使是同一个组件,这个函数也不会为子元素运行。

【问题讨论】:

    标签: reactjs recursion rerender memo


    【解决方案1】:

    我发现了原因,我在导出上做了备忘录,所以孩子们使用的组件不是记忆的,我的错。

    【讨论】:

    • 避免这种错误的一种方法可能是 - 为 UnMemoized 组件指定一个不同的名称,与 Memoized 不同的名称。例如:export default function CommentCardGroup__() { ...const CommentCardGroup = React.memo(CommentCardGroup__, areEqual)
    • 是的,这就是我为解决问题所做的:const MemoCommentCardGroupReact = React.memo(CommentCardGroup, equal); export default MemoCommentCardGroupReact; 然后使用了 MemoCommentCardGroupReact 一个;
    猜你喜欢
    • 1970-01-01
    • 2019-12-21
    • 2021-12-04
    • 1970-01-01
    • 2021-10-23
    • 2023-01-28
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多