简体   繁体   English

防止在反应js中重新渲染子组件

[英]prevent re render in child component in react js

I have a counter app.我有一个计数器应用程序。 I need to prevent re-render component.我需要防止重新渲染组件。 I want to execute Childcompnent only when I clicking on update, but here it is executing both time when I click count or update.我只想在单击更新时执行Childcompnent ,但在这里当我单击计数或更新时它都会执行。

import { useCallback, useMemo, useState } from "react";

export const App = () => {
  const [count, setCount] = useState(0);
  const [updatecount, setUpdateCount] = useState(0);

  const incCount = () => {
    setCount(parseInt(count) + 1);
  };

  const updCount = useCallback(() => {
    return setUpdateCount(parseInt(updatecount) + 1);
  }, [updatecount]);

  return (
    <>
      <button onClick={incCount}>count</button>
      <button onClick={updCount}>update</button>
      <Childcompnent count={count} />
      <p>{updatecount}</p>
    </>
  );

};

export default App;

export function Childcompnent({ count }) {
  console.log("pressed");
  return <p>{count}</p>;
}

Wrap your Childcompnent in React.memo :将您的Childcompnent包装在React.memo中:

const Childcompnent = React.memo(({ count }) => {
  console.log("pressed");
  return <p>{count}</p>;
});

Here is the sandbox:这是沙箱:

编辑 serverless-wood-ro6iek

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

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