React Native:Flash 消息内存泄漏错误 代码错误代码

问题描述

我在 React Native 中使用 Flash Message。当我导航到另一个屏幕而不等待消息消失时,会引发内存泄漏错误

代码

showMessage({
  message: "Hello World",duration: 2000,description: "This is our second message",type: "success",});

错误

Warning: Can't perform a React state update on an unmounted component. This is a no-op,but it indicates a memory leak in your application. To fix,cancel all subscriptions and asynchronous tasks in %s.%s,the componentwillUnmount method,

解决方法

您无需等待 Flash 消息消失。您可以在导航到新屏幕之前以编程方式隐藏消息。

代码


// import hideMessage method from the library
import { hideMessage } from "react-native-flash-message";

// a function which navigates to another screen
foo = () => {
  // assuming you are using react navigation
  // in a class based component
  const { navigation } = this.props;

  // call hideMessage before you navigate
  hideMessage();
  navigation.navigate('ScreenName');
}
,

useEffect() 的解决方案

import { hideMessage } from "react-native-flash-message";


  useEffect(() => {
    return () => {
      hideMessage()
    }
  },[])