当我在 React Native 中导航到新页面时,如何强制卸载组件?
How do I force a component to unmount when I navigate to a new page in react native?
我想确保生命周期方法 ComponentWillUnmount 在我导航到新页面时触发。我找到了这个 post, but that doesn't seem to mention anything about navigating to a new page. I also found this 但我正在使用反应导航。此外,我没有使用 pop/push。我只是使用 this.props.navigation.navigate('SomePage') 进入下一页
查看 React Navigation
处理组件生命周期事件的方法 in their docs here
TL;DR,您可以签出 React Navigation
's navigation lifecycle event 以在切换屏幕时执行操作。希望对你有帮助。
您可以使用 this.props.navigation.replace('routName');
它会完成你的工作。
React 导航永远不会破坏屏幕。这意味着您的屏幕永远不会卸载,或者当您返回时它永远不会重新安装 (didMount
)。为此,您必须使用 useFocusEffect
import React, { useCallback } from 'react';
import { useFocusEffect } from '@react-navigation/native';
const Home = () => {
useFocusEffect(
useCallback(() => {
// Do something when the screen is focused/mount
return () => {
// Do something when the screen is unfocused/unmount
// Useful for cleanup functions
};
}, [])
);
return <Home />;
}
参考:导航生命周期
我想确保生命周期方法 ComponentWillUnmount 在我导航到新页面时触发。我找到了这个 post, but that doesn't seem to mention anything about navigating to a new page. I also found this
查看 React Navigation
处理组件生命周期事件的方法 in their docs here
TL;DR,您可以签出 React Navigation
's navigation lifecycle event 以在切换屏幕时执行操作。希望对你有帮助。
您可以使用 this.props.navigation.replace('routName');
它会完成你的工作。
React 导航永远不会破坏屏幕。这意味着您的屏幕永远不会卸载,或者当您返回时它永远不会重新安装 (didMount
)。为此,您必须使用 useFocusEffect
import React, { useCallback } from 'react';
import { useFocusEffect } from '@react-navigation/native';
const Home = () => {
useFocusEffect(
useCallback(() => {
// Do something when the screen is focused/mount
return () => {
// Do something when the screen is unfocused/unmount
// Useful for cleanup functions
};
}, [])
);
return <Home />;
}
参考:导航生命周期