react控制反转


react控制反转

一种减少子组件重渲的性能优化的手段

// 先来看父组件重渲子组件也重渲的方式

// 这种方式 count 每加一次 父组件和子组件都会重渲

import { useState } from "react"

const Father = () => {
  const [count, setCount] = useState(0);
  console.log("Father rendered");
  return (
    <>
      <p>I am Father p tag, {count}</p>
      <button onClick={() => setCount(count + 1)}>Add Count</button>
      <br />
      <Children />
    </>
  );
};

const Children = () => {
  console.log("Children rendered");
  return <p>I am Children p tag</p>;
};
// count 增加 父子组件都不会重渲

// 原因: 省流描述 -> 因为 children 来自于父组件,子组件的重新渲染并不会导致其也重新渲染。
import { useState } from "react";

const Father = () => {
  console.log("Father rendered");
  return (
    <FatherIoc>
      <br />
      <Children />
    </FatherIoc>
  );
};

const FatherIoc = ({ children }) => {
  const [count, setCount] = useState(0);
  return (
    <>
      <p>I am Father p tag, {count}</p>
      <button onClick={() => setCount(count + 1)}>Add Count</button>
      {children}
    </>
  );
};

const Children = () => {
  console.log("Children rendered");
  return <p>I am Children p tag</p>;
};
参考资料: https://juejin.cn/post/7146405884938158116#comment

文章作者: KarlFranz
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 reprint policy. If reproduced, please indicate source KarlFranz !
评论
  目录