美文网首页
阻止组件重新渲染

阻止组件重新渲染

作者: 海豚先生的博客 | 来源:发表于2024-01-10 17:34 被阅读0次

重新渲染的起因:

  • 组件的state变化
  • 父组件重新渲染
  • 组件使用context,provider的value发生变化时

子组件使用useContext导致的重渲染

// value是个复杂类型的对象,父组件的重渲染会导致重新生成{mode}
const ThemeContext = React.createContext<Theme>({ mode: 'light' });
const useTheme = () => {
  return useContext(ThemeContext);
};
// before:
// 父组件
const [mode, setMode] = useState<Mode>("light");
return (
    <ThemeContext.Provider value={{ mode }}>
      // 这里有个计数器点击+1
      // 这里有个按钮可以切换主题模式
    </ThemeContext.Provider>
  );
const Item = ({ country }: { country: Country }) => {
    // 父组件计数器+1,这里每次会是个新对象,导致重渲染
    const { mode } = useTheme();
    const className = `country-item ${mode === "dark" ? "dark" : ""}`;
    // the rest is the same
}

// after:
const [mode, setMode] = useState<Mode>("light");
// memoising the object! 缓存对象
  const theme = useMemo(() => ({ mode }), [mode]);
return (
    <ThemeContext.Provider value={theme}>
      <button onClick={() => setMode(mode === 'light' ? 'dark' : 'light')}>Toggle theme</button>
      // 这里有个计数器,可以点击+1
      // 这里有个按钮可以切换主题模式
    </ThemeContext.Provider>
  )
// 子组件
const Item = ({ country }: { country: Country }) => {
    // 父组件计数器+1,这里每次是个同一个对象,不会重渲染
    // 切换主题会导致子组件重新渲染
    const { mode } = useTheme();
    const className = `country-item ${mode === "dark" ? "dark" : ""}`;
    // the rest is the same
}

React.memo,将组件缓存

// 只要props中的属性(a,或者其他更多的参数)没有变化,MovingComponent 的重渲染不会导致ChildComponent 的重渲染
// 如果props中有函数参数,在父组件中应使用useCallback包裹,以保持父组件每次重渲染时,传递给子组件的函数引用地址一致
const ChildComponent = (props) {
  ...
  return (
      <div onClick={props.onClick}>{props.a}</div>
  )
}
export default React.memo(ChildComponent)

const MovingComponent = () => {
const [state, setState] = useState({ x: 100, y: 100 });
const onClick = useCallback(() => {
    console.log('xxx')
}, [])
return (
  <div
    onMouseMove={(e) => setState({ x: e.clientX - 20, y: e.clientY - 20 })}
    style={{ left: state.x, top: state.y }}
  >
    // MovingComponent的重渲染不会导致ChildComponent 的重渲染
    <ChildComponent a={111} onClick={onClick} />
  </div>
);
};


抽离为children,以避免重渲染

# 鼠标移动后,MovingComponent 会重渲染,导致子组件ChildComponent 重渲染,如果后者很“重”,将导致性能问题
const MovingComponent = () => {
  const [state, setState] = useState({ x: 100, y: 100 });

  return (
    <div
      // when the mouse moves inside this component, update the state
      onMouseMove={(e) => setState({ x: e.clientX - 20, y: e.clientY - 20 })}
      // use this state right away - the component will follow mouse movements
      style={{ left: state.x, top: state.y }}
    >
      <ChildComponent />
    </div>
  );
};
// ChildComponent 通过children 传递,MovingComponent 的重渲染不会导致ChildComponent 重渲染,因为ChildComponent 隶属于组件SomeOutsideComponent,组件作为children传递不会重渲染,因为它是props,它在SomeOutsideComponent 组件中已经创建完毕,已经调用过React.createElement了
const MovingComponent = ({ children }) => {
  const [state, setState] = useState({ x: 100, y: 100 });

  return (
    <div onMouseMove={(e) => setState({ x: e.clientX - 20, y: e.clientY - 20 })} style={{ left: state.x, top: state.y }}>
      // children now will not be re-rendered
      {children}
    </div>
  );
};

const SomeOutsideComponent = () => {
  return (
    <MovingComponent>
      <ChildComponent />
    </MovingComponent>
  );
};

Mystery 1: why components that are passed as props don’t re-render?

为什么通过props传递一个组件,父组件重渲染不会使该组件重渲染?
Answer 1: “children” is a <ChildComponent /> element that is created in SomeOutsideComponent. When MovingComponent re-renders because of its state change, its props stay the same. Therefore any Element (i.e. definition object) that comes from props won’t be re-created, and therefore re-renders of those components won’t happen.

Mystery 2: if children are passed as a render function, they start re-rendering. Why?

为什么将props.children通过一个函数传递,会导致重渲染?

const MovingComponent = ({ children }) => {
  // this will trigger re-render
  const [state, setState] = useState();
  return (
    <div ///...
    >
      <!-- those will re-render because of the state change -->
      {children()}
    </div>
  );
};

const SomeOutsideComponent = () => {
  return (
    <MovingComponent>
      {() => <ChildComponent />}
    </MovingComponent>
  )
}
Answer 2:In this case “children” are a function, and the Element (definition object) is the result of calling this function. We call this function inside MovingComponent, i.e. we will call it on every re-render. Therefore on every re-render, we will re-create the definition object <ChildComponent />, which as a result will trigger ChildComponent’s re-render.

Mystery 3: MovingComponentMemo使用memo,为什么没有阻止由于SomeOutsideComponent 重渲染导致ChildComponent 的重渲染

// wrapping MovingComponent in memo to prevent it from re-rendering
const MovingComponentMemo = React.memo(MovingComponent);

const SomeOutsideComponent = () => {
  // trigger re-renders here with state
  const [state, setState] = useState();

  return (
    <MovingComponentMemo>
      <!-- ChildComponent will re-render when SomeOutsideComponent re-renders -->
      <ChildComponent />
    </MovingComponentMemo>
  )
}

const MovingComponent = ({children}) => <>{children}</>
Answer 3:因为SomeOutsideComponent 的每次重渲染都重新创建了ChildComponent (是个对象),MovingComponentMemo会检查props是否变动,即检查props.children,因为ChildComponent 是重新生成的,与之前的不相等(2个对象的地址不相等),所以会触发重渲染;如果将ChildComponent 使用memo包裹,则MovingComponent的重渲染不会导致ChildComponent 重渲染,因为MovingComponent检查发现这个props与之前的相等

Mystery 4: when passing children as a function, why memoizing this function doesn’t work?

将Mystery 2中的函数使用useCallback包裹,还是阻止不了重渲染?

const SomeOutsideComponent = () => {
  // trigger re-renders here with state
  const [state, setState] = useState();

  // this memoization doesn't prevent re-renders of ChildComponent
  const child = useCallback(() => <ChildComponent />, []);

  return <MovingComponent>{child}</MovingComponent>;
};

const MovingComponent = ({ children }) => {
  // this will trigger re-render
  const [state, setState] = useState();
  return (
    <div ///...
    >
      <!-- those will re-render because of the state change -->
      {children()}
    </div>
  );
};
child函数被记忆,但是它的返回结果(<ChildComponent />)没有被记忆,同一个函数每次都会执行React.createElement,即重渲染

参考
https://www.developerway.com/posts/react-elements-children-parents

相关文章

  • react Hooks —— memo用法

    改变Parent组件中的num,会重新渲染Child组;改变Parent组件中的count,不会重新渲染Child组件

  • useCallback

    简介 1 .优化子组件的渲染次数2 .父组件重新渲染组件的时候,传给子组件的函数类型的props也会重新生成,所以...

  • react中通过props给子组件传值,为什么当父组件setSt

    父组件代码 当父组件setState变化asset值,就会重新渲染子组件使用asset里的属性做渲染,直接使用th...

  • React函数组件优化

    主要针对于函数组件,父组件重渲染时,减少子组件不必要的渲染。 性能优化方向 1.减少重新 render 的次数 2...

  • Component.setState()详解

    setState() API setState()方法主要是用来更新组件状态,让组件重新渲染。 应该将setSta...

  • keep-alive缓存组件及应用案例

    一、keep-alive组件: 缓存组件 作用: 可以让组件保留状态,避免重新渲染,提升页面性能 二、举例: 在...

  • Vue3_20(keep-alive缓存组件)

    内置组件keep-alive 有时候我们不希望组件被重新渲染影响使用体验;或者处于性能考虑,避免多次重复渲染降低性...

  • React 生命周期

    React 生命周期 初始化周期 组件重新渲染生命周期 组件卸载生命周期

  • react-native知识点

    react-native知识点 PureComponent是纯组件 即无状态组件,更新state不会触发重新渲染,...

  • VUE----keep-alive

    有时候我们不希望组件被重新渲染影响使用体验;或者处于性能考虑,避免多次重复渲染降低性能。而是希望组件可以缓存下来,...

网友评论

      本文标题:阻止组件重新渲染

      本文链接:https://www.haomeiwen.com/subject/njzondtx.html