1 introduction

RN novice, just started, so this article is suitable for beginners or basic developers to watch, I hope you can help.

React Router is used to manage routes when developing web pages using React Native. React Navigation. First of all, I think the API design is great.

2 the installation

yarn add @react-navigation/native 
yarn add react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view 

Copy the code

3 Basic concepts that must be mastered

To learn React Navigation, you must master the following points.

3.1 Screen – The official documentation

React Native has many screens. The concept is similar to Route in React Router, which connects routes with components.

// React Router 
<Route path="/login" component={LoginComponent} /> 
// React navigation 
<Stack.Screen name="Login" component={LoginScreen} />
Copy the code

3.2 Navigators – The official documentation

Navigators allow you to define the navigation structure of your project and support many configurations, such as Headers, TAB bars, etc. The React Router is similar to the Router in React Router. A Router is responsible for jumping between a group of routes. Similarly, a Navigator is also responsible for the mutual jump of a group of screens. In practical use, React Navigation has a layer of encapsulation, which encapsulates several commonly used layouts into different Navigators.

3.2.1 Stack the Navigator -The official documentation

The Stack Navigator is basically equivalent to Router + Switch, which switches the entire page every time you Switch

// React Router peers <Suspense fallback={<LoadableLoading />}> <Router history={history}> <Switch> <Route path="/login" component={Login} /> </Switch> </Router> </Suspense> // React Navigation Stack Navigator <RootSiblingParent> <Provider store={store}> <SafeAreaView style={styles.container}> <NavigationContainer> <Stack.Navigator initialRouteName='logged'>  <Stack.Screen name='Login' component={LoginScreen} options={{ headerShown: false }} /> <<Stack.Navigator/> </NavigationContainer> </SafeAreaView> </Provider> </RootSiblingParent>Copy the code

3.2.2 the Drawer the Navigator -The official documentation

Drawer Navigation is similar to adding a Drawer component to the Router + Switch component. This component is placed in the parent component and is displayed when accessing each child path.

// React Route
 <Router>
    <Route name="/" component={DrawerComponent} />
    <Switch>
      <Route name="/home" component={HomeComponent} />
      <Route name="/ddd" component={DddComponent} />
    </Switch>
  </Router>
  
 //Drawer Navigator
<NavigationContainer>
    <Drawer.Navigator>
      <Drawer.Screen name="Home" component={HomeScreen} />
      <Drawer.Screen name="Notifications" component={NotificationsScreen} />
    </Drawer.Navigator>
</NavigationContainer>

Copy the code

Bottoms Tab Navigator -The official documentation

Drawer Navigator is similar to adding a bottom Tab component to the Router + Switch component. This component is placed in the parent component and is displayed when accessing each child path

 //Drawer Navigator
 import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

const Tab = createBottomTabNavigator();
<NavigationContainer>
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="ddd" component={DddScreen} />
    </Tab.Navigator>
</NavigationContainer>
Copy the code

3.2.4 Material Bottoms Tab Navigator – The official documentation

Drawer Navigator is similar to adding a bottom Tab component to the Router + Switch component. This component is placed in the parent component and is displayed when accessing each child path

 //Drawer Navigator
 import { createMaterialBottomTabNavigator } from '@react-navigation/bottom-tabs';

const Tab = createMaterialBottomTabNavigator();
<NavigationContainer>
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeScreen} />
      <Tab.Screen name="ddd" component={DddScreen} />
    </Tab.Navigator>
</NavigationContainer>
Copy the code

3.3 Jumps and page stacks

Similar to the browser, Native also uses stacks to store access history records. However, unlike the browser, which only has two operations of loading and unloading a page, Native provides more interfaces for page stack operation. React Navigation is packaged into several apis on this interface.

3.3.1 Navigation. Navigate (screen) Pushes a new page

  • If this Screen is already present, it will not jump

  • If there is already a Screen in the page stack, all screens on that Screen are pushed off the stack

3.3.2 Navigation. Push (screen) pushes the new page

Note: If you already have this Screen, there will be two of the same Screen in the stack

3.3.3 Navigation. Replace (screen) replace current page (to be paid until payment is complete page backstep does not need to be paid to be used

3.3.4 Navigation. Goback (screen) Step back one page to close the current page

3.3.5 Navigation. Pop () returns to the previous page by default

3.3.6 Navigation. PopToTop () returns to the topmost page

  • Go to the first page – that is, keep only the bottom page of the page stack, and remove all other pages from the stack

4 Page life cycle and useHooks(important)

I will just list the hooks that ARE frequently used, if you are interested go to the official website for more. In a Web environment, we tend to focus on three life cycles,

  • Mount: page creation
  • Update: updates the page
  • Destroy: the page is destroyed or logged out

For Native environments, there are two additional page life cycles to be concerned about in addition to the ones above

  • App cuts to the background
  • App cuts back to the foreground

4.1 addListener – The official documentation

const unsubscribe = navigation.addListener('tabPress', (e) => {
  // Prevent default action
  e.preventDefault();
});
function Profile({ navigation }) {
  React.useEffect(() => {
    const unsubscribe = navigation.addListener('focus', () => {
      // do something
    });
    return unsubscribe;
  }, [navigation]);
  return <ProfileContent />;
}

Copy the code
  • Focus – Emits this event when the screen is in focus

  • Blur – This event is emitted when the screen is out of focus

  • BeforeRemove – Prevents users from leaving when they leave the screen

  • State (Advanced)- emits this event when the state of the navigator changes

  • TabPress (Advanced) – Listens for TAB page switching

4.2 useFocusEffect – The official documentation

React Navigation encapsulates useFocusEffect and uses a useEffect like design

import { useFocusEffect } from '@react-navigation/native';
function Profile({ userId }) {
const [user, setUser] = React.useState(null);
useFocusEffect(
    React.useCallback(() => {
        const unsubscribe = API.subscribe(userId, user => setUser(user));
        return () => unsubscribe();
        }, [userId])

    );
    return <ProfileContent user={user} />;
}
Copy the code

4.3 useIsFocused – The official documentation

Determine the focus state of the current page

Note: this hook triggers the renders re- link. If you have too many renders we recommend using React. UseMemo or React.PureCompnent to reduce re-renders.

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

function Profile() {
const isFocused = useIsFocused();
return <Text>{isFocused ? 'focused' : 'unfocused'}</Text>;
}
Copy the code

4.4 useNavigation – The official documentation

This hook is similar to the useHistory function in the React Router, useNavigation, which can access a navigation object. This method can be used when you don’t want to use a pass-by-pass navigation.

import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';
function MyBackButton() {
    const navigation = useNavigation();
    return (
        <Button
        title="Back"
        onPress={() => {
            navigation.goBack();
            }}
        />
    );
}
Copy the code

4.5 useRoute – The official documentation

It can be used to obtain the object of the route argument, similar to the useLocation of the React Router,

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

function MyText() {
  const route = useRoute();

  return <Text>{route.params.caption}</Text>;
}

Copy the code

Common page-level architectures

The pages commonly used in our general app are Login, LoggedScreen and Setting. The simple hierarchy diagram is as follows:

So let’s combine Sreen and navigation again

The last

React Router and React Navigation are great libraries that simulate multiple pages on one page and are highly usable.