使用 React.memo、useCallback、useMemo 防止对象重新渲染

时间:2021-06-18 12:57:31

标签: reactjs react-hooks usecallback react-usememo

防止原始值的重新渲染工作正常(React.memo)但是当我尝试将对象传递给子组件时问题就开始了。我尝试使用 useMemo 和 useCallback 但没有成功。 唯一的解决方案是使用 JSON.srtingify() 传递数据,然后在子组件中使用 JSON.parse() - 但这个解决方案看起来很糟糕。

import React, {useState} from 'react';

const TextExample1 = ({name, surname, infoText}) => {
  console.log(infoText);
  return (
    <p>
      {infoText} {name} {surname}
    </p>
  );
};

const TextExample2 = React.memo(({name, surname, infoText}) => {
  console.log(infoText);
  return (
    <p>
      {infoText} {name} {surname}
    </p>
  );
});

const TextExample3 = React.memo(({data, infoText}) => {
  console.log(infoText);
  return (
    <p>
      {infoText} {data.name} {data.surname}
    </p>
  );
});

const TextExample4 = React.memo(({data, infoText}) => {
  console.log(infoText);
  const parsedData = JSON.parse(data);
  return (
    <p>
      {infoText} {parsedData.name} {parsedData.surname}
    </p>
  );
});

const App = () => {
  console.log('----- NEW RENDER -----');
  const [forceRerenderNumber, setForceRerenderNumber] = useState(0);

  const sourceData = {
    name: 'Joe',
    surname: 'Moore',
  };

  return (
    <div>
      <TextExample1
        name="Joe"
        surname="Moore"
        infoText="1 - Works fine - intented rerenders :)"
      />
      <TextExample2
        name="Joe"
        surname="Moore"
        infoText="2 - Works fine - intented no rerenders. Rendered only onece :)"
      />
      <TextExample3
        data={sourceData}
        infoText="3 - Doesn't work fine - there are unintented rerendars :( How to stop it?"
      />
      <TextExample4
        data={JSON.stringify(sourceData)}
        infoText="4 - Works. - intented no rerenders. But JSON.stringify() and JSON.parse() looks like really hacky way. How to improve it?"
      />
      <Button
        onClick={() => {
          setForceRerenderNumber(forceRerenderNumber + 1);
        }}>
        Rerender
      </Button>
    </div>
  );
};

export default App;

日志:

 LOG  ----- NEW RENDER -----
 LOG  1 - Works fine - intented rerenders :)
 LOG  2 - Works fine - intented no rerenders with primitive data. Rendered only onece :)
 LOG  3 - Doesn't work fine - there are unintented rerendars :( How to stop it?
 LOG  4 - Works. - intented no rerenders. But JSON.stringify() and JSON.parse() looks like really hacky way. How to improve it?
 LOG  ----- NEW RENDER -----
 LOG  1 - Works fine - intented rerenders :)
 LOG  3 - Doesn't work fine - there are unintented rerendars :( How to stop it?
 LOG  ----- NEW RENDER -----
 LOG  1 - Works fine - intented rerenders :)
 LOG  3 - Doesn't work fine - there are unintented rerendars :( How to stop it?

1 个答案:

答案 0 :(得分:0)

如果 Find 是一个不变的常量,你可以把它放在组件之外:

sourceData

如果const sourceData = { name: "Joe", surname: "Moore", }; const App = () => {} 可以改变,你可以使用sourceData

useMemo