gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:02:24 27 4
gpt4 key购买 nike

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

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

最佳答案

正如一些答案所说,您可以使用 React.PureComponent 它可以避免以任何理由重新渲染它,因此您可以修复它,将您的 IframeReact.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>
);
}
}

因此 MyPureIframe 只会在它的某些属性发生变化(src、宽度、高度或您传递的其他值)时发生变化(重新渲染)。

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

希望对您有所帮助。

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>
);
}
}

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

希望对你有帮助。

关于javascript - 如何防止 React 重新渲染整个组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52874300/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com