¿Cómo puedo ejecutar la misma función en cada pantalla con React Navigation? Estoy usando React Native y TypeScript. Tengo una navegación con home , profile , etc...
Tengo la siguiente función y quiero que se ejecute cuando navegues a profile , home , etc.
const getFunction = (): void => { console.log("execute function"); };Probé el siguiente código pero no funciona:
useEffect(() => { const listener = navigation.addListener("focus", (e) => { getFunction(); }); return () => listener; }, [navigation]);Una descripción general de mis pantallas:
return ( ... <Stack.Screen name='home' component={home} /> <Stack.Screen name='profile' component={profile} /> ... )por favor si me pudieras ayudar te lo agradeceria mucho!! :)
Puede usar screenListeners prop en el navegador. De esta forma, puede especificar oyentes para eventos de todas las pantallas. Como ejemplo así:
<Stack.Navigator screenListeners={{ focus: (e) => { // code you wanna execute goes here console.log("Focus has changed") }, }} > <Stack.Screen name="home" component={home} /> <Stack.Screen name="profile" component={profile} /> </Stack.Navigator>