当父组件重新渲染时,例如更新自身状态等时。
当子组件的 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中文网其他相关文章!