reactjs - 组件渲染 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);
解决方案
该itemCount
道具告诉 FixedSizeList 要渲染多少行,因此无论列表中有多少项目,您的列表都会渲染props.patients
,这最终来自过滤父组件中 fetch 返回的数组的结果。index
您在 Row 组件中使用的prop 从 FixedSizeList 传递给 Row 并引用其在列表中的位置,因此它告诉 Row 组件的第一个实例其索引为 0,并且 Row 使用该信息来呈现data.patients
道具中第一个项目的名称。FixedSizeList 将自己的itemData
prop 作为 Row 的 prop 传递给每个 Row 组件data
。
来自FixedSizeList 组件的 react-window 文档:
itemCount: 数量
列表中的项目总数。请注意,一次只会渲染和显示几个项目。
和
孩子:组件
React 组件负责渲染由索引道具指定的单个项目
您将 Row 组件作为子级传递给 FixedSizeList,因此它会itemCount
多次呈现 Row 组件。
React memo 不会影响组件的实例数。如果 props 没有更改,所有 memo 所做的都是通过重用其最后渲染的版本来潜在地提高渲染每个实例的性能。
推荐阅读
- google-cloud-platform - eclipse中gcp的凭据
- git - 在现有提交中隐藏 GitHub 上的 API 密钥
- html - 对齐弹性框中的最后一行
- python - Firefox 无法使用 geckodriver 打开
- flutter - 每次视图进入屏幕时如何在颤动中重建整个视图
- java - 从二进制堆转储中提取 JVM 正常运行时间
- python - Python argparse -h 选项点缀
- php - 使用修改过的 MustVerifyEmail 特征的 Laravel API 无法获取请求用户
- kotlin - Swagger-UI 和 Ktor 如何导入 swagger.json 或 .yaml 文件并启动 Swagger-UI?
- python - matplotlib 按钮在嵌套的 GridSpec 中不起作用