gpt4 book ai didi

reactjs - React 服务端渲染内存泄漏

转载 作者:行者123 更新时间:2023-12-03 14:17:48 25 4
gpt4 key购买 nike

下面的代码根据链接react说:

Unfortunately, this can cause memory leaks for server rendering (where componentWillUnmount will never be called)

// Before
class ExampleComponent extends React.Component {
componentWillMount() {
this.setState({
subscribedValue: this.props.dataSource.value,
});

// This is not safe; it can leak!
this.props.dataSource.subscribe(
this.handleSubscriptionChange
);
}

componentWillUnmount() {
this.props.dataSource.unsubscribe(
this.handleSubscriptionChange
);
}

handleSubscriptionChange = dataSource => {
this.setState({
subscribedValue: dataSource.value,
});
};
}

我无法理解这怎么可能是服务器端的内存泄漏。例如,假设我们有这段在服务器端呈现的代码,并且 ExampleComponent 包含内存泄漏。

import React from 'react';
import ReactDomServer from 'react-dom/server';
import App from './components/index'

const serverRender = () =>{
return ReactDomServer.renderToString(<ExampleComponent />);
};

export default serverRender;

当它返回到客户端时,渲染的组件不会附加到任何地方,并准备好进行 GB 收集。那么为什么会出现内存泄漏呢?

最佳答案

文档中暗示了答案:

People often assume that componentWillMount and componentWillUnmount are always paired, but that is not guaranteed

明显的原因是 componentWillMount 在组件即将安装时运行,因此如果安装被中断,则组件将永远不会安装,因此永远不会卸载。但是,文档的上一部分也显示了代码的暗示原因:

componentWillMount() {

this.setState({
subscribedValue: this.props.dataSource.value,
});

// This is not safe; it can leak!
this.props.dataSource.subscribe(
this.handleSubscriptionChange
);

}

并说

The above code is problematic for both server rendering (where the external data won’t be used) and the upcoming async rendering mode (where the request might be initiated multiple times).

据此可以假设 componentWillMount 确实在 SSR 期间运行,并且在客户端水合时也运行,这意味着发出了额外的不必要的请求,导致服务器上潜在的内存泄漏。

但是,如果您使用 componentDidMount 那么这可以保证:

  1. 仅在客户端运行
  2. 确保 componentWillUnmount 之后始终运行

关于reactjs - React 服务端渲染内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55294658/

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