【问题标题】:How to find out memory leaks in react native app?如何找出反应本机应用程序中的内存泄漏?
【发布时间】:2019-08-09 21:56:15
【问题描述】:

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

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

但我不知道如何从堆内存中删除数据。数据是否在每次导航时都存储在heap 中?所以这会使应用程序的性能非常缓慢。不知道我说的对不对很好的帮助。谢谢!

【问题讨论】:

  • 您是否删除了componentWillUnmount 中的所有计时器和事件监听器?
  • 您可以使用 Android 上的 Android Studio Profiler 工具和 iOS 上的 Debug navigator 来寻找内存泄漏。
  • @NilsKähler 是的,我正在卸载 eventlisteners 。所以在 android studio 中,它会显示内存泄漏发生在哪里以及如何发生?
  • 如果你去分析器,那么你会看到你的记忆图,然后你可以看到每次你路由到一个新页面或执行一个动作时记忆是否增加。

标签: javascript reactjs react-native memory-management memory-leaks


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,帮助的方法很少:

    使用 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;
    

    【讨论】:

    • 这两种方法我都试过了,但还是一样
    猜你喜欢
    • 2020-03-05
    • 2011-02-25
    • 1970-01-01
    • 2015-12-30
    • 2022-01-13
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2019-10-18
    相关资源
    最近更新 更多