首頁 > web前端 > js教程 > 主體

React 基礎知識~渲染效能/備忘錄

DDD
發布: 2024-10-14 16:35:31
原創
860 人瀏覽過
  • 這些是子元件將被渲染的模式。
  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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!