繁体   English   中英

如何找出反应本机应用程序中的内存泄漏?

[英]How to find out memory leaks in react native app?

我已经在 react native AsyncStorage构建了一个学习管理系统应用程序。我正在使用AsyncStorage进行简单的状态管理,而根本没有使用 redux。我现在面临的问题是我是否要通过执行来连续使用该应用程序不同的操作然后应用程序变得非常慢。我认为这是内存泄漏,因为当我从后台杀死应用程序并再次打开它时,它可以毫不延迟地工作。所以我不知道如何避免这种内存泄漏。我已经尝试了很多解决方案

  1. 从应用程序中删除了所有console.log
  2. 更改了所有内联样式
  3. 使用ComponentDidMount而不是ComponentWillMount
  4. 尝试预取数据。

但是我不知道如何从堆内存中删除数据。每次导航时数据是否都存储在heap ?所以这会使应用程序的性能非常慢。 不知道我说的对不对。如果我的概念有任何错误请见谅。现在没有时间将状态管理更改为redux 。请帮助我找到解决方案,这将是一个很大的帮助。谢谢!

我遇到了同样的问题,一些有帮助的方法是:

使用转换删除控制台:

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;

我也有同样的问题,因为在未安装的组件上调用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);
  };
}

暂无
暂无

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

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