如何在React Native应用程序中查找内存泄漏?

15
我在React Native Android中构建了一个学习管理系统应用程序。我使用AsyncStorage进行简单的状态管理,而没有使用redux。我现在面临的问题是,如果我通过执行不同的操作持续使用该应用程序,则应用程序变得非常缓慢。我认为这是内存泄漏,因为当我从后台杀死应用程序并再次打开它时,它可以正常工作而没有任何延迟。所以我不知道如何避免这种内存泄漏。我尝试过很多解决方案:
  1. 从应用程序中删除所有console.log
  2. 更改所有内联样式
  3. 使用ComponentDidMount代替ComponentWillMount
  4. 尝试数据预取。
但我不知道如何从堆内存中移除数据。在每个导航上,数据是否被存储在heap中?这会使应用程序的性能非常慢。我不知道我是否正确,请原谅我的理念中是否有任何错误。现在没有时间将状态管理更改为redux。请帮助我找到解决方案,这将是一项巨大的帮助。谢谢!

2
你在 componentWillUnmount 中移除了所有的定时器和事件监听器吗? - Nils Kähler
您可以使用Android Studio Profiler工具在Android上,或使用iOS上的Debug Navigator来查找内存泄漏。 - Nils Kähler
@NilsKähler 是的,我正在卸载事件监听器。那么在Android Studio中,它会显示内存泄漏发生的位置和方式吗? - Linu Sherin
如果您前往分析器,您将会看到一个内存图表,然后您可以查看内存是否在每次路由到新页面或执行操作时增加。 - Nils Kähler
2个回答

9

我曾经遇到同样的问题,以下是一些有帮助的方法:

使用 transform-remove-console:

https://www.npmjs.com/package/babel-plugin-transform-remove-console

将其添加到您的生产环境 Babel 插件并安装它。它将在生产中隐藏应用程序中的所有控制台日志。

添加已挂载状态

具体而言,在未安装的组件中调用 setState() 意味着组件已卸载后您的应用程序仍然持有对该组件的引用,这通常表示存在内存泄漏!

https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html

import React, { Component } from 'react';


class App extends Component {

  _isMounted = false;

  componentDidMount() {
    this._isMounted = true;
    // ... do your stuff here
  }

  componentWillUnmount() {
    // tells the component that component is now unmounted
    this._isMounted = false;
  }

  getUsersFromApi(){
    if(this._isMounted){
      // ... tasks
    }
  }

}

export default App;

3
我已尝试这两种方法。但是反应仍然相同。 - Linu Sherin

6

我也遇到了同样的问题,因为在未挂载的组件上调用了 setState 导致。

因此,对于任何有状态的基于类的组件,我通常都会采用这个模板:

我忘记了 setState(),而是使用了下面声明的 setComponentState

class MyComponent extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      // other fields...

    };
    this.isUnmounted =  true,
  }

  componentDidMount(){
      this.isUnmounted =  false;
  }

  componentWillUnmount() {
      this.isUnmounted = true;
  }

  setComponentState = (values) => {
    if (!this.isUnmounted) this.setState(values);
  };
}

你能展示这个函数组件的实现吗?如何使用 useState,并通过这种方式获取它的值。 - Samiksha Jagtap

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接