即使将备忘录设置为子组件,子组件仍然可以重新渲染。
这是一种我们将函数作为 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;
const clickHandler = () => { setCountB((pre) => pre + 1); };
<Child countB={countB} onClick={clickHandler} />
const clickHandler = useCallback(() => { setCountB((pre) => pre + 1); }, []);
以上是React 基础知识~渲染性能/ useCallback的详细内容。更多信息请关注PHP中文网其他相关文章!