- 这些是子组件将被渲染的模式。
当父组件重新渲染时,例如更新自身状态等时。
当子组件的 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 (
parent component
update the state of parent component
update the state of child component
the count of clicked:{counta}
);
};
export default example;
・src/child .js
const child = ({ countb }) => {
console.log("%cchild render", "color: red;");
return (
child component
the count of b button cliked:{countb}
);
};
export default child;
- 在这种情况下,当我们按下 a(父组件)按钮时,子组件就会被渲染。虽然没有必要。
・像这样。
・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 (
Child component
The count of B button cliked:{countB}
);
}, areEqual);
export default ChildMemo;
- 如果我们使用memo,我们可以避免不必要的重新渲染。
・像这样。











