当父组件重新渲染时,例如更新自身状态等时。
当子组件的 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中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号