React 基础知识~渲染性能/备忘录
收藏
最近发现不少小伙伴都对文章很感兴趣,所以今天继续给大家介绍文章相关的知识,本文《React 基础知识~渲染性能/备忘录》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~
- 这些是子组件将被渲染的模式。
-
当父组件重新渲染时,例如更新自身状态等时。
-
当子组件的 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;
- 在这种情况下,当我们按下 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,我们可以避免不必要的重新渲染。
・像这样。
理论要掌握,实操不能落!以上关于《React 基础知识~渲染性能/备忘录》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注米云公众号吧!
版本声明 本文转载于:dev.to 如有侵犯,请联系删除
- 努比亚手机如何连接电脑?
