这些是子组件将被渲染的模式。
当父组件重新渲染时,例如更新自身状态等时。
当子组件的 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,我们可以避免不必要的重新渲染。
・像这样。
以上就是React 基础知识~渲染性能/备忘录的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1493250.html
微信扫一扫
支付宝扫一扫