【问题标题】:component is not unmounting react-native组件没有卸载 react-native
【发布时间】:2021-07-10 18:07:58
【问题描述】:

在我的代码中,我遇到了卸载组件的问题。我正在使用抽屉导航器,当我在抽屉屏幕之间导航时,前一个屏幕并没有消失,当我再次打开该屏幕时,一切仍然存在。

但是当我在抽屉屏幕之间导航时,我想重新渲染或卸载并再次安装组件。有办法吗?或者我怎样才能让我的组件手动卸载?我知道对此有很多问题,但我找不到我想要的。

我的 react native 版本是 0.63

【问题讨论】:

    标签: javascript reactjs react-native react-navigation


    【解决方案1】:

    你应该检查react-navigation documentation的这个页面

    考虑一个带有屏幕 A 和 B 的堆栈导航器。导航到 A、它的componentDidMount被调用。当推 B 时,它的 componentDidMount 也被调用,但 A 仍然安装在堆栈上 因此它的 componentWillUnmount 不会被调用。

    结论,屏幕不会在您每次导航时被破坏和重新创建,这是设计使然。

    如果您想在离开或再次打开页面时执行一些代码,您应该使用lifecycle events presented in the same documentation

    【讨论】:

      【解决方案2】:

      react 导航永远不会破坏屏幕。这意味着您的屏幕永远不会卸载,或者当您返回时它永远不会重新安装(didMount)。要执行此操作,请参见下面的示例

      import React, { useCallback } from 'react';
      import { useFocusEffect } from '@react-navigation/native';
      
      const Home = () => {
        useFocusEffect(
          useCallback(() => {
            // Do something when the screen is focused
      
            return () => {
              // Do something when the screen is unfocused
              // Useful for cleanup functions
            };
          }, [])
        );
      
        return <Home />;
      }
      

      参考:Navigation Lifecycle

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-19
        • 2017-10-12
        • 1970-01-01
        • 2015-07-26
        • 1970-01-01
        • 2017-11-06
        • 1970-01-01
        相关资源
        最近更新 更多