首页  >  文章  >  web前端  >  React 基础知识~渲染性能/备忘录

React 基础知识~渲染性能/备忘录

DDD
DDD原创
2024-10-14 16:35:31863浏览
  • 这些是子组件将被渲染的模式。
  1. 当父组件重新渲染时,例如更新自身状态等时。

  2. 当子组件的 props 重新渲染时。

但实际上,只有渲染 props 时才需要重新渲染子组件。其他一切都是不必要的。

・src/Example.js

mport React, { useState } from "react";
import Child from "./Child";
import "./Example.css";

const Example = () => {
  console.log("Parent render");
  const [countA, setCountA] = useState(0);
  const [countB, setCountB] = useState(0);
  return (
    <div className="parent">
      <div>
        <h3>Parent Component</h3>
        <div>
          <button
            onClick={() => {
              setCountA((pre) => pre + 1);
            }}
          >
            Button A
          </button>
          <span>Update the state of Parent Component</span>
        </div>
        <div>
          <button
            onClick={() => {
              setCountB((pre) => pre + 1);
            }}
          >
            Buton B
          </button>
          <span>Update the state of Child Component</span>
        </div>
      </div>
      <div>
        <p>The count of clicked:{countA}</p>
      </div>
      <Child countB={countB} />
    </div>
  );
};

export default Example;

・src/Child .js

const Child = ({ countB }) => {
  console.log("%cChild render", "color: red;");

  return (
    <div className="child">
      <h2>Child component</h2>
      <span>The count of B button cliked:{countB}</span>
    </div>
  );
};

export default Child;

  • 在这种情况下,当我们按下 A(父组件)按钮时,子组件就会被渲染。虽然没有必要。

・像这样。
React Basics~Render Performance/ memo

・src/Child .js​(使用备忘录钩子)

import { memo } from "react";

function areEqual(prevProps, nextProps) {
  if (prevProps.countB !== nextProps.countB) {
    return false; // re-rendered
  } else {
    return true; // not-re-rendred
  }
}

const ChildMemo = memo(({ countB }) => {
  console.log("%cChild render", "color: red;");

  return (
    <div className="child">
      <h2>Child component</h2>
      <span>The count of B button cliked:{countB}</span>
    </div>
  );
}, areEqual);

export default ChildMemo;

  • 如果我们使用memo,我们可以避免不必要的重新渲染。

・像这样。
React Basics~Render Performance/ memo

以上是React 基础知识~渲染性能/备忘录的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
上一篇:React Hooks with Example下一篇:暂无