简体   繁体   English

即使在使用 memo 和 useCallback 后 React 组件也会重新渲染

[英]React component re-rendering even after using memo and useCallback

The entire list gets re-rendered instead of the particular selected list item upon state change在 state 更改时,整个列表将重新呈现,而不是特定的选定列表项

https://codesandbox.io/s/lfgxe (Refer the console to see components that gets rendered) https://codesandbox.io/s/lfgxe (请参阅控制台以查看被渲染的组件)

When the "add to the main array" button is clicked, the array(state) has to get updated and only the particular list item has to be re-rendered.单击“添加到主数组”按钮时,必须更新数组(状态),并且必须重新渲染特定的列表项。 But all the items in the list are re-rendered.但是列表中的所有项目都被重新渲染。 I tried passing key prop, memo, callbacks they but didn't work.我尝试传递关键道具、备忘录、回调,但没有奏效。

Links that I referred to:我提到的链接:

  1. https://alexsidorenko.com/blog/react-list-rerender/ https://alexsidorenko.com/blog/react-list-rerender/

  2. https://dmitripavlutin.com/dont-overuse-react-usecallback/ https://dmitripavlutin.com/dont-overuse-react-usecallback/

App.js:应用程序.js:


export default function App() {
  const [value5, setValue5] = useState([]);
  let a = [1, 2, 3, 4, 5, 6];
  console.log("===========Parent component called ======================");

  let buttonClick = useCallback((keyID) => {
    setValue5((c) => [...c, keyID]);
  }, []);
  console.log(value5);
  return (
    <div className="App">
      {a.map((i) => {
        return (
          <MapperComp buttonClick={buttonClick} keyID={i} key={i.toString()}>
            <h1>{i} from the app.js</h1>
            <h1>{i} from the app.js</h1>
          </MapperComp>
        );
      })}
    </div>
  );
}

MapperComp.js : MapperComp.js

import React, { memo } from "react";

const MapperComp = memo(({ buttonClick, keyID, ...props }) => {
  console.log("component", keyID);

  return (
    <div>
      <div>
        <h1>{keyID}</h1>
        {props.children}
        <button
          onClick={() => {
            buttonClick(keyID);
          }}
        >
          Add to the main array
        </button>
      </div>
    </div>
  );
});

export default MapperComp;

You have used useCallback for buttonClick that will not redefine the function.您已将useCallback用于buttonClick ,它不会重新定义 function。 But setValues will update values state and re-render the whole component.但是setValues将更新values state 并重新渲染整个组件。 For solving it, you should wrap this list in useMemo adding a in the dependency array.为了解决这个问题,您应该将此列表包装在useMemo中,并在依赖数组中添加a

const list = useMemo(() => {
   return (
      a.map((i) => {
        return (
          <MapperComp buttonClick={buttonClick} keyID={i} key={i.toString()}>
            <h1>{i} from the app.js</h1>
            <h1>{i} from the app.js</h1>
          </MapperComp>
        );
      }
   );
}, [a])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM