【问题标题】:how to avoid all child component re-render without override shouldComponentUpdate in child component如何避免所有子组件在子组件中不覆盖 shouldComponentUpdate 的情况下重新渲染
【发布时间】:2021-01-04 11:34:02
【问题描述】:

这是一个很常见的场景,我们有一个包含大量数据的表。每行都有一个复选框,用于从选定行导出数据。

在 App.tsx 中,

const App = () => {
  const [selection, setSelection] = useState<string[]>([]);

  const handleSelect = useCallback(
    (name: string) => {
      if (selection.includes(name)) {
        selection.splice(selection.indexOf(name), 1);
        setSelection([...selection]);

        return;
      }

      setSelection([...selection, name]);
    },
    [selection, setSelection]
  );

  return (
    <Paper>
      <TableContainer>
        <Table stickyHeader aria-label="sticky table">
          <TableHead>
            ...
          </TableHead>
          <TableBody>
            {rows.map((row) => {
              return (
                <Row
                  key={row.name}
                  row={row}
                  selected={selection.includes(row.name)}
                  onSelect={handleSelect}
                />
              );
            })}
          </TableBody>
        </Table>
      </TableContainer>
    </Paper>
  );
};

在 Row.jsx 中,

export const Row = React.memo(
  ({ selected, row, onSelect }: RowProps) => {
    const handleSelect = () => {
      onSelect(row.name);
    };

    return (
      <TableRow key={row.code}>
        <TableCell key="checkbox">
          <Checkbox checked={selected} onChange={handleSelect} />
        </TableCell>
        // render other columns ...
      </TableRow>
    );
  }
);

以上是基本的代码结构。 My problem is that when a row is selected/deselected, the app will be re-rendered since the state refreshed, that will cause callback instance refreshed as well, then all child Row will be re-rendered which I want to avoid because of performance问题。 useCallback 不适用于这种情况,因为它依赖于 selection 状态。

我知道我可以在子组件中实现 shouldComponentUpdate,只是想知道是否可以从 root 解决问题?

感谢您的任何建议,祝您新年快乐。

更新: 将 parent 改为 React.Component 而不是 function 组件可以解决问题,因为 setState 不会刷新回调实例。我认为这两种组件几乎相同,但显然它们是不同的。希望它可以帮助某人,但仍然想知道是否可以在功能组件中存档。

【问题讨论】:

    标签: javascript reactjs usecallback


    【解决方案1】:

    您可以通过多种方式进行操作,这里我提到了一对。

    1. 您可以将 arePropsEqual 函数与您的自定义实现一起传递给子组件中的 React.memo 函数。
    2. 目前您正在将一个对象(行)传递给子组件。而不是传递对象分别传递每个单独的道具。组件在渲染组件之前会进行浅层比较。如果你传递一个对象浅比较总是返回道具不相等,这就是它重新渲染的原因。

    【讨论】:

    • 感谢您的回复,但正如我所描述的,我正在寻找除了 shouldComponentUpdate 之外的其他解决方案,arePropsEqual 是一回事。导致子组件的原因不是行数据,我可以确认行数据没有改变,是在App.tsx(父组件)中选择状态改变后会重新生成哪个实例的onSelect回调。
    猜你喜欢
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2018-12-24
    • 2018-06-10
    • 2023-01-28
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多