登录
首页 >  文章 >  前端

React Basics~Render Performance/ useCallback

来源:dev.to

时间:2024-10-27 12:30:52 271浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《React Basics~Render Performance/ useCallback》,以下内容主要包含等知识点,如果你正在学习或准备学习文章,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

  • 即使将备忘录设置为子组件,子组件仍然可以重新渲染。

  • 这是一种我们将函数作为 props 传递给子组件的情况。

・src/example.js

import react, { usecallback, usestate } from "react";
import child from "./child";

const example = () => {
  console.log("parent render");

  const [counta, setcounta] = usestate(0);
  const [countb, setcountb] = usestate(0);

  const clickhandler = () => {
    setcountb((pre) => pre + 1);
  };

  return (
    <div classname="parent">
      <div>
        <h3>parent component</h3>
        <div>
          <button
            onclick={() => {
              setcounta((pre) => pre + 1);
            }}
          >
            button a
          </button>
          <span>update parent component</span>
        </div>
      </div>
      <div>
        <p>the count of click button a:{counta}</p>
      </div>
      <child countb={countb} onclick={clickhandler} />
    </div>
  );
};

export default example;


・src/child.js

import { memo } from "react";

const childmemo = memo(({ countb, onclick }) => {
  console.log("%cchild render", "color: red;");

  return (
    <div classname="child">
      <h2>child component</h2>
      <div>
        <button onclick={onclick}>button b</button>
        <span>uodate child component</span>
      </div>
      <span>the count of click button b :{countb}</span>
    </div>
  );
});

export default childmemo;


  • 子组件重新渲染的原因是因为src/example.js中的clickhandler函数
  const clickhandler = () => {
    setcountb((pre) => pre + 1);
  };
  • 此函数作为 onclick 属性传递给子组件。
 <child countb={countb} onclick={clickhandler} />
  • 如果我们用 usecallback 包装子组件,我们可以避免这种情况。
  const clickHandler = useCallback(() => {
    setCountB((pre) => pre + 1);
  }, []);

React Basics~Render Performance/ useCallback

React Basics~Render Performance/ useCallback

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>