简体   繁体   English

组件未卸载 react-native

[英]component is not unmounting react-native

In my code I have a problem with unmount a component.在我的代码中,我遇到了卸载组件的问题。 I am using drawer-navigator and when i navigating between drawer-screens the previous screen is not dying and when i open that screen again everything is still there.我正在使用抽屉导航器,当我在抽屉屏幕之间导航时,前一个屏幕并没有消失,当我再次打开该屏幕时,一切都还在那里。

But i want to re-render or unmount and mount the component again when i navigate between drawer-screens.但是当我在抽屉屏幕之间导航时,我想重新渲染或卸载并再次安装组件。 Is there a way for that?有办法吗? Or how can i make my component unmount manually?或者我怎样才能让我的组件手动卸载? I know there is a lot of question about this but i couldn't find that i want.我知道对此有很多问题,但我找不到我想要的。

My react native version is 0.63我的反应原生版本是 0.63

You should check this page of react-navigation documentation您应该查看react-navigation 文档的此页面

Consider a stack navigator with screens A and B. After navigating to A, its componentDidMount is called.考虑一个带有屏幕 A 和 B 的堆栈导航器。导航到 A 后,它的 componentDidMount 被调用。 When pushing B, its componentDidMount is also called, but A remains mounted on the stack and its componentWillUnmount is therefore not called.在压入 B 时,它的 componentDidMount 也会被调用,但 A 仍然挂载在堆栈上,因此不会调用它的 componentWillUnmount。

Conclusion, the screens are not detroyed and re-created everytime you navigate, it's by design.结论,屏幕不会在您每次导航时被破坏和重新创建,这是设计使然。

If you want to execute some code when you leave or open again a page you should use the lifecycle events presented in the same documentation如果您想在离开或再次打开页面时执行一些代码,您应该使用同一文档中提供的生命周期事件

react navigation never destroy the screen.反应导航永远不会破坏屏幕。 Its mean your screen will never unMount or when you go back it will never remount (didMount).这意味着您的屏幕永远不会卸载,或者当您返回 go 时,它永远不会重新安装(didMount)。 To Perform such see the example below要执行此操作,请参见下面的示例

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 />;
}

Reference: Navigation Lifecycle参考: 导航生命周期

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

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