登录
首页 >  文章 >  前端

React 基础知识~渲染性能/备忘录

来源:dev.to

时间:2024-11-22 18:22:01 263浏览 收藏

最近发现不少小伙伴都对文章很感兴趣,所以今天继续给大家介绍文章相关的知识,本文《React 基础知识~渲染性能/备忘录》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

  • 这些是子组件将被渲染的模式。
  1. 当父组件重新渲染时,例如更新自身状态等时。

  2. 当子组件的 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 基础知识~渲染性能/备忘录》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:dev.to 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>