简体   繁体   中英

How to reload a component in a bottom tab navigator

I have 4 bottom tab navigator options

        <Tab.Screen name="Home" component={HomeScreen} options={{headerShown:false}}/>
        <Tab.Screen name="Appointments" component={Doctors}/>
        <Tab.Screen name="Lab Tests" component={Diagnostics}/>
        <Tab.Screen name="Account" component={Profile} options={{ unmountOnBlur: true }}

In the Account tab, I am showing the Profile Details And Edit Profile option.

Clicking on Edit Profile I go to Edit Profile Page, Edit Save,

  const Save = navigation.navigate("Account")

After hitting Save, I am returned to the Account tab but the component Profile, which I am using as an Account tab component, is not reloading, so the Profile Details I am using are still the old Details.

As You Can see I already used unmountOnBlur: true , It works only when I am switching tabs, I want the same behavior when I came back from the Edit Profile page to the Account Tab.

If your getting the profile data from an API's that means your calling the same API in the Account Tab as well. You can add an event listener and every time your screen get into focus you can call that apis and get the updated result.

Ref: https://reactnavigation.org/docs/navigation-events .

Example:

React.useEffect(() => {
    const unsubscribe = props.navigation.addListener('focus', () => {
      // call your api here
    });

    return unsubscribe;
  }, [navigation]);

Without a complete example, it's hard to figure out the exact issue. Maybe the profile component is using the useEffect without deps will not call again.

You can Call a function when focused screen changes or re-render a screen with the useIsFocused hook -

useIsFocused - this will cause a re-render. May introduce unnecessary component re-renders as a screen comes in and out of focus.

import * as React from 'react';
import { Text } from 'react-native';
import { useIsFocused } from '@react-navigation/native';

function Profile() {
  // This hook returns `true` if the screen is focused, `false` otherwise
  const isFocused = useIsFocused();
  ......
}

Or Triggering an action with a focus event listener , you can control the re-renders

React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      // screen is focused
    });

    // Return the function to unsubscribe from the event so it gets removed on unmount
    return unsubscribe;
  }, [navigation]);

There's also a useFocusEffect .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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