正如一些答案所述,你可以使用 React.PureComponent
来避免无谓的重新渲染,这样你就可以解决问题,将你的 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>
<MyPureIframe src={'https://your-url-to-iframe'} width={100} height={100} />
</div>
);
}
}
因此,只有当MyPureIframe
的某些props发生更改(例如src、width、height或您传递的其他props)时,它才会改变(重新渲染)。
因此,在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>
<MyPureIframe src={'https://your-url-to-iframe'} width={100} height={100} />
</div>
);
}
}
这样做,您将获得相同的结果,但是使用函数组件。
希望能对您有所帮助。
isMobile
从未更改,则只需使用React.PureComponent,那么iframe就不会重新渲染。 - Fabio AntunessetState
? - HMRpath=something.concat(another)
的方式从父组件设置props,则每次渲染都会更改props。您应该发布将props传递给组件的部分。 - HMR