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 (    

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(父组件)按钮时,子组件就会被渲染。虽然没有必要。

・像这样。
React 基础知识~渲染性能/备忘录

・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 基础知识~渲染性能/备忘录

以上就是React 基础知识~渲染性能/备忘录的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2664508.html

(0)
上一篇 2025年3月7日 11:39:33
下一篇 2025年2月27日 09:41:32

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论