文本字段不必要的重新渲染

Ran*_*own 5 reactjs material-ui

我注意到一个问题,当不相关的状态/属性发生变化时,同一父级中的每个组件(下面示例中的应用程序)都会重新渲染,从而使页面/表单明显变慢。

我遵循了许多建议,例如记住事件处理程序和道具,但不相关的组件仍然会重新渲染。我很困惑。我对 React 有什么不理解的地方?

[ CodeSandbox ] 在 React 调试器中,启用:组件渲染时突出显示更新

import React, { useMemo, useState } from "react";
import { TextField } from "@material-ui/core";

function MyTextInput(props) {
  return (
    <TextField
      variant={"outlined"}
      onChange={props.onChange}
      value={props.value}
    />
  );
}

export default function App() {
  const [exampleTextValue1, setExampleTextValue1] = useState("");
  const [exampleTextValue2, setExampleTextValue2] = useState("");

  const handleChange1 = useMemo(
    () => (event) => setExampleTextValue1(event.target.value),
    []
  );

  const handleChange2 = useMemo(
    () => (event) => setExampleTextValue2(event.target.value),
    []
  );

  return (
    <>
      <div>
        Change me:
        <MyTextInput value={exampleTextValue1} onChange={handleChange1} />
      </div>

      <div>
        Unrelated inputs. Should not re-render:
        <MyTextInput value={exampleTextValue2} onChange={handleChange2} />
        <MyTextInput value={exampleTextValue2} onChange={handleChange2} />
        {/*  to feel the impact, copy the above line like 98 more times  */}
      </div>
    </>
  );
}

Run Code Online (Sandbox Code Playgroud)

Jay*_*444 3

调试器工具在记忆组件方面存在缺陷。当您记住组件时,它们实际上不会重新渲染,但调试工具无论如何都会突出显示它们(请参阅https://github.com/facebook/react/issues/19778)。

要实际测试重新渲染,请将第二个输入(已渲染多次)的默认状态值更改为“test”之类的值,然后将其放入console.log记忆MyTextInput组件中以查看哪些组件实际上正在重新渲染:

const MyTextInput = React.memo((props) => {
  console.log(props.value);
  return (
    <TextField
      variant={"outlined"}
      onChange={props.onChange}
      value={props.value}
      disabled={props.disabled}
    />
  );
});
Run Code Online (Sandbox Code Playgroud)

console.log您可以看到它在第一次渲染时为所有第二个输入打印一次“测试”值,然后当您输入第一个输入时,由于记忆化,它不会记录所有第二个输入。

  • 就是这样。“React.memo”创造了奇迹。我们还确认调试器会错误地突出显示未发生渲染的渲染。谢谢您的帮助! (2认同)