- 这些是子组件将被渲染的模式。
当父组件重新渲染时,例如更新自身状态等时。
当子组件的 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 class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/ai/1195" title="LOGO.com"><img
src="https://img.php.cn/upload/ai_manual/000/000/000/175680118939474.png" alt="LOGO.com" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/ai/1195" title="LOGO.com">LOGO.com</a>
<p>在线生成Logo,100%免费</p>
</div>
<a href="/ai/1195" title="LOGO.com" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>
</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;
- 在这种情况下,当我们按下 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 (
<div className="child">
<h2>Child component</h2>
<span>The count of B button cliked:{countB}</span>
</div>
);
}, areEqual);
export default ChildMemo;
- 如果我们使用memo,我们可以避免不必要的重新渲染。
・像这样。










