即使将备忘录设置为子组件,子组件仍然可以重新渲染。
这是一种我们将函数作为 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 (
parent component
update parent component
the count of click button a:{counta}
);
};
export default example;
・src/child.js
import { memo } from "react";
const childmemo = memo(({ countb, onclick }) => {
console.log("%cchild render", "color: red;");
return (
child component
uodate child component
the count of click button b :{countb}
);
});
export default childmemo;
- 子组件重新渲染的原因是因为src/example.js中的clickhandler函数
const clickhandler = () => {
setcountb((pre) => pre + 1);
};
- 此函数作为 onclick 属性传递给子组件。
- 如果我们用 usecallback 包装子组件,我们可以避免这种情况。
const clickHandler = useCallback(() => {
setCountB((pre) => pre + 1);
}, []);












