Mobile 개발/RN(React Native)

RN - stack 이동시 새로 고침(refresh)

히핑소 2020. 12. 5. 15:24
반응형

React Native 에서

stackNavigator 와 BottomTabNavigator 사용 시

stack 이동 할 때마다, bottomTab 이동 할 때 마다

새로 고침 또는 새로 lifecycle 을 태울 때 필요한 code가 있습니다.

그렇지 않으면 stack 첫 이동 시 '생성 될 때' lifecycle만,

이후에는 '업데이트 할 때' 에 해당되는 lifecycle 만 타게됩니다.

해당 option 을 추가하면, stack 이동 시 constructor - render - componentDidMount 가 항상 불리기 때문에

본인 application 이 이방식에 적절하다면 아래 code를 반드시 추가해줘야 합니다.

StackNavigator - reactnavigation.org/docs/navigation-actions/#reset

 

CommonActions reference | React Navigation

A navigation action is an object containing at least a type property. Internally, the action can be handled by routers with the getStateForAction method to return a new state from an existing navigation state.

reactnavigation.org

ProfileScreen 이동 시 항상 새로 시작:

navigation.dispatch( CommonActions.navigate("ProfileScreen")); 

default 방식: navigation.navigate("ProfileScreen");

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home!</Text>
      <Button
        title="Navigate to Profile"
        onPress={() =>
          navigation.dispatch(
            CommonActions.navigate({
              name: 'Profile',
              params: {
                user: 'jane',
              },
            })
          )
        }
      />
      <Button
        title="Go back"
        onPress={() => navigation.dispatch(CommonActions.goBack())}
      />
    </View>
  );
}

function ProfileScreen({ navigation, route }) {
  return (
  )
 }

 

 

BottomTabNavigator - reactnavigation.org/docs/bottom-tab-navigator/#unmountonblur

 

createBottomTabNavigator | React Navigation

A simple tab bar on the bottom of the screen that lets you switch between different routes. Routes are lazily initialized -- their screen components are not mounted until they are first focused.

reactnavigation.org

bottomTab 은 간단하게, options 에 unmountOnBlur 만 추가해주면 됩니다.

import {NavigationContainer} from '@react-navigation/native';
import {createBottomTabNavigator} from "@react-navigation/bottom-tabs";
import {createStackNavigator} from "@react-navigation/stack";

import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import FoundationIcons from 'react-native-vector-icons/Foundation';
import Ionicons from 'react-native-vector-icons/Ionicons';

import React, { useEffect } from 'react'
import SplashScreen from 'react-native-splash-screen'

const Tab = createBottomTabNavigator();
const Stack = createStackNavigator();

export default function MainScreen() {
  useEffect(() => {
    setTimeout(() => {
        SplashScreen.hide();
    }, 1000);
  }, [])
  
  return (
    <NavigationContainer>
        <Stack.Navigator>
            <Stack.Screen name="Auth" component={AuthScreen} 
            options={() => ({
              headerShown:false,
              headerTitle:"로그인",
            })}
            />
            <Stack.Screen name="Home" component={HomeScreen}
            options={() => ({
              // headerLeft:() => <Header left={true} navigation={navigation}/>,
              // headerRight:() => <Header left={false} navigation={navigation}/>,
              // headerLeft:null,
              // headerTitleAlign:"center",
              headerShown:false,
              headerTitle:"홈",
            })}
            />
            <Stack.Screen name="LocationSetting" component={LocationSetting}
            options={() => ({
              headerTitleAlign:"center",
              headerTitle:"지역 설정",
            })}
            />
            <Stack.Screen name="Setting" component={Setting}
            options={() => ({
              headerTitleAlign:"center",
              headerTitle:"설정",
            })}
            />
            <Stack.Screen name="AppManual" component={AppManual}
            options={() => ({
              headerTitleAlign:"center",
              headerTitle:"앱 설명",
            })}
            />
        </Stack.Navigator>
    </NavigationContainer>
  );
}

function HomeScreen() {
  return (
    <Tab.Navigator 
      tabBarOptions={{
      activeTintColor: '#ffffff',}}>
        <Tab.Screen name={"First"} component={Home}
            options={{
              tabBarIcon: ({ color, size }) => (
                <Ionicons name="ios-rest" color={color} size={size} />
              ),
              tabBarLabel:"첫번째",
              unmountOnBlur: Platform.OS === 'ios' ? false : true,
            }}
        />
        <Tab.Screen name={"Second"} component={Home}
            options={{
              tabBarIcon: ({ color, size }) => (
                <MaterialCommunityIcons name="truck" color={color} size={size} />
              ),
              tabBarLabel:"두번째",
              unmountOnBlur: Platform.OS === 'ios' ? false : true,
            }}
        />
    </Tab.Navigator>
  );
}

 

반응형