首页 > 解决方案 > 组件渲染 8 次

问题描述

我不清楚为什么 Row 组件渲染了 8 次。我应该在 React Memo 中为此组件使用自定义比较功能吗?我正在使用react-window包。请解释它如何为我工作。非常感谢。

ListView 的父组件:CovidMap 组件

我的整个项目:Github

这是我的代码:

import React, { useRef, memo, useEffect } from 'react';
import { FixedSizeList as FixedList, areEqual } from 'react-window';
import './ListView.scss';

const ListView = (props) => {
  const listRef = useRef();

  const Row = memo((props) => {
    console.log('Row rendering...');
    const { data, index, style } = props;
    const className =
      data.itemIndex === index
        ? 'PatienIndicator Highlight'
        : 'PatientIndicator';
    return (
      <button
        key={index}
        className={className}
        onClick={() => data.onClickPatient(data.patients[index])}
        style={style}
      >
        {data.patients[index].name}
      </button>
    );
  }, areEqual);

  const patientsLength = props.patients
    ? Object.keys(props.patients).length
    : 0;

  const data = Object.assign(
    {},
    { patients: props.patients },
    { onClickPatient: props.onClickPatient },
    { itemIndex: props.itemIndex }
  );

  console.log('List View rendering...');

  useEffect(() => {
    if (props.itemIndex) {
      listRef.current.scrollToItem(props.itemIndex, 'smarter');
    }
  });

  return (
    <FixedList
      className="List"
      height={300}
      itemCount={patientsLength}
      itemSize={50}
      width={'100%'}
      ref={listRef}
      itemData={data}
    >
      {Row}
    </FixedList>
  );
};

export default memo(ListView);

标签: reactjs

解决方案


itemCount道具告诉 FixedSizeList 要渲染多少行,因此无论列表中有多少项目,您的列表都会渲染props.patients,这最终来自过滤父组件中 fetch 返回的数组的结果。index您在 Row 组件中使用的prop 从 FixedSizeList 传递给 Row 并引用其在列表中的位置,因此它告诉 Row 组件的第一个实例其索引为 0,并且 Row 使用该信息来呈现data.patients道具中第一个项目的名称。FixedSizeList 将自己的itemDataprop 作为 Row 的 prop 传递给每个 Row 组件data

来自FixedSizeList 组件的 react-window 文档

itemCount: 数量

列表中的项目总数。请注意,一次只会渲染和显示几个项目。

孩子:组件

React 组件负责渲染由索引道具指定的单个项目

您将 Row 组件作为子级传递给 FixedSizeList,因此它会itemCount多次呈现 Row 组件。

React memo 不会影响组件的实例数。如果 props 没有更改,所有 memo 所做的都是通过重用其最后渲染的版本来潜在地提高渲染每个实例的性能。


推荐阅读