如何防止 React 重新渲染整个组件

dav*_*orb 6 javascript reactjs

我有一个名为isMobile显示外部 iframe的道具。当我在 iPad 上倾斜屏幕时,这将更改道具以更改值并重新渲染 iframe(丢失 iframe 内的所有进度)。

防止重新渲染的好方法是什么?该文档说,我不应该使用shouldComponentUpdate,因为只有一个性能优化。

Juo*_*lez 5

正如一些答案所说,您可以使用 a React.PureComponentthat it 避免以任何理由重新渲染,因此您可以修复它,将您Iframe的组件分离为单个组件,React.PureComponent因此它会是这样的:

class MyPureIframe extends React.PureComponent {
  render() {
    const {src, width, height} = this.props;
    return (
      <iframe src={src} width={width} height={height} {...whateverProps} />
    );
  }
}

class MyNormalView extends React.Component {
  render() {
    return (
      <div>
       <!--SOME MARKUP HERE-->
       <MyPureIframe src={'https://your-url-to-iframe'} width={100} height={100} />
       <!--SOME MARKUP HERE-->
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

所以MyPureIframe当它的一些道具改变(src、宽度、高度或其他你传递的)时,唯一会改变(重新渲染)。

这样,在MyNormalView重新渲染中,深层组件MyPureIframe不会重新渲染,直到它的任何 props 发生变化。

我希望它能帮助你。

2020 年 5 月更新

因为上面的答案与基于类的组件有关,如果您使用功能组件,它意味着呈现一些 html 标记的函数,您仍然可以使用这种方法如下。

import React, {memo} from 'react';

const MyPureIframe = memo(({src, width, height}) => (
  <iframe src={src} width={width} height={height} {...whateverProps}/>
));

class MyNormalView extends React.Component {
  render() {
    return (
      <div>
       <!--SOME MARKUP HERE-->
       <MyPureIframe src={'https://your-url-to-iframe'} width={100} height={100} />
       <!--SOME MARKUP HERE-->
      </div>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

这样做,您将获得相同的结果,但使用功能组件代替。

希望对你有帮助。


Arc*_*ika 0

shouldComponentUpdate 并不是更好的方法。该文档表示将来可以忽略对 shouldComponentUpdate 的更改。memoize请尝试使用比 PureComponent 更好的概念

  • 您能提供一些代码来解释这个概念吗?对于人们在您的答案中阅读的信息来说,这将是有用的信息。 (3认同)