Home > OS >  How to reset/rerender screen you just left with react navigation
How to reset/rerender screen you just left with react navigation

Time:01-17

So, exactly what the title says, I'm making a react native app and I want the screen that I leave with navigation.navigate() to be "reset" or "rerendered" when I come back to it, because as it is now, when I leave the screen and then come back to it it's state is the same as I left it. Here's the navigator code

const Tab = createBottomTabNavigator();

export default function App() {

  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Group>
        <Tab.Screen name="Devices" component={Devices} options={{
          tabBarIcon:({focused})=>(
            <View style={{alignItems:'center', justifyContent:'center'}}>
              <Image
                source={require('./android/app/src/main/assets/devices.png')}
                resizeMode='contain'
                style={{
                  width: 30,
                  height: 30
                }}
              />
            </View>
          )
        }} />
        <Tab.Screen name="Connection" component={ConnectionScreen} options={{
          tabBarIcon:({focused})=>(
            <View style={{alignItems:'center', justifyContent:'center'}}>
              <Image
                source={require('./android/app/src/main/assets/connection.png')}
                resizeMode='contain'
                style={{
                  width: 30,
                  height: 30
                }}
              />
            </View>
          )
        }} />
        </Tab.Group>
        <Tab.Group screenOptions={{ presentation: 'modal' }}>
          <Tab.Screen name='Add device' component={AddDevice}
          options={{   
            tabBarButton: () => null,
            tabBarVisible:false
          }}/>
        </Tab.Group>
      </Tab.Navigator>
    </NavigationContainer>
  );
}

And the second smaller thing is, that I can't see any navigation aniamtions, like this Modal on the bottom for example

CodePudding user response:

Set unmountOnBlur to true

Unmounting a screen resets any local state in the screen as well as the state of the nested navigators in the screen. Defaults to false.

<Tab.Navigator
  screenOptions={{ unmountOnBlur: true }}
>
...
</Tab.Navigator>

Also, you can apply it to a single route:

<Tab.Navigator>
  <Tab.Screen name="..." component={...} options={{ unmountOnBlur: true }} />
</Tab.Navigator>

CodePudding user response:

You can make use of useIsFocused, try something like:

import { useIsFocused } from '@react-navigation/native';

  const isFocused = useIsFocused();

useEffect(() => {
    //executes whenever this component/screen is focused
  }, [isFocused]);

You can also set the unmountOnBlur flag to true to the particular screen as below:

<Tab.Screen
    name={...}
    component={...}
    options={{unmountOnBlur: true}}
/>
  •  Tags:  
  • Related