繁体   English   中英

具有内存泄漏的React组件

[英]React Component with Memory Leak

我有一段遗留代码,它在每次请求时在服务器上呈现一个react组件,这显然存在内存泄漏。 我已经解决了这个代码的问题:

  componentWillMount: function () {
    var onLogin = this.props.onLogin || function () {},
        onLogout = this.props.onLogout || function () {};

    this.on('authChange', function () {
      console.log('user authenticated:', this.state.isAuthenticated);
      return this.state.isAuthenticated
              ? onLogin(this.state)
              : onLogout(this.state);
    }.bind(this));
  },

我相信在每个请求中, this对象都存储了一个新的监听器,但我不明白为什么在完成组件的渲染时, this元素没有被标记为垃圾。

在卸载组件之前,需要取消绑定authChange处理程序。 您可以在componentWillUnmount执行此操作。

由于您使用传入的第一个道具创建处理函数,因此应将其保存到属性中,以便以后可以取消绑定:

  componentWillMount: function () {
    var onLogin = this.props.onLogin || function () {},
        onLogout = this.props.onLogout || function () {};

    this.authChange = function () {
      console.log('user authenticated:', this.state.isAuthenticated);
      return this.state.isAuthenticated
              ? onLogin(this.state)
              : onLogout(this.state);
    }.bind(this);

    this.on('authChange', this.authChange);
  },

  componentWillUnmount: function () {
      this.off('authChange', this.authChange);
      this.authChange = null;
  }

需要注意的是,当我看到this.on我想你可能会使用jQuery,但目前尚不清楚这将是这种情况。 我的回答使用this.off来分离事件监听器,但是您应该使用框架中相应方法的任何内容。

我会将您的函数移动到componentDidMount并在componentWillUnmount上添加清理

重要提示componentWillMount被称为服务器 客户端 ,但componentDidMount只调用客户端上。

如果您正在使用eventListenerssetInterval或其他需要清理的函数,请将它们放在componentDidMount 服务器不会调用componentWillUnmount ,通常是内存泄漏的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM