preface
There are no beforeEnter and routerWillLeave hook functions in react navigation, which makes intercepting the page more complicated.
Fortunately, you can see the custom route provided by the official
getStateForAction
Let’s look at the method declaration first
- Action Specifies the current user action, such as NAVIGATE or REPLACE
- State All information about the current navigation stack
Then debug looks at the concrete structure,
From the debug message, you can see that the action is the parameter to the navigate method each time we call it
/ / this call navigate method. Props. Navigation. Navigate ('InfoChart', {
city_id: "balabalabalabala"
});
Copy the code
State is all information in the current navigation stack
The official website does not see the Chinese translation, here is only the English translation, the main meaning is:
Takes the current state and action, which contains routename and routeParamList, and returns a new state after processing.
In other words, after the state is changed, the return comes out, and the react-navigation can realize the page jump.
How to determine which page the user enters from?
As stated above, the action has routename inside
With the source of the page and the method of intercepting the page, go ahead and implement it
index.js
+ import Filter from './Filter'; Const AppStack = createStackNavigator(routeConfigMap, stackConfig); + / / intercept routing stack on the surface of the inside pages jump + AppStack router. GetStateForAction = Filter (AppStack); filter.jsexport default functionFilter (stack) {/ / 1. Save the stack first instance methods, for page release const NAVIGATE = stack. The router. GetStateForAction; // 2. We block all user related pages and let them go to the login page if they are not logged inif (['Check'.'Pay'.'Receipt'].includes(action.routeName)) { const token = utils.getToken(); // Intercept the user who is not logged inif(! Parse (json.stringify (state)) const res = json.parse (json.stringify (state)); res.routes.push({ key: routeKey, routeName:'Login'}); res.index = res.routes.length - 1;returnres; }}} // Finally test in simulator or real machineCopy the code
getStateForRouteNamesChange
This method is not found in the source code, welcome to the research of this method in the comments section
Something to watch out for
-
Do not modify parameters directly inside a method, nor do you shallow copy them. Since the state here is a reference type, the state only passes the address when it is passed. If the parameter value is changed, the value of state in memory will be changed, thus affecting the operation of other functions in the react-Navigation, so we need to copy a deeper layer.
-
This article only intercepts pages within a Navigation stack, if nesting of stacks is used, it is necessary to intercept the stack recursively or individually