當父元件重新渲染時,例如更新自身狀態等。
當子元件的 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;
・像這樣。
・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;
・像這樣。
以上是React 基礎知識~渲染效能/備忘錄的詳細內容。更多資訊請關注PHP中文網其他相關文章!