# Page routing listening
Start from base library version 3.5.5. Please remaining backward compatible.
This guide mainly describes the use of the_page routing event listener function_available from the base library version {% version (3.5.5)%}.If you need basic information about the type and logic of page routing, you can refer to page routing .
Because each routing can trigger multiple page lifecycles for multiple pages at a time, when a certain lifecycle of a page is triggered, Weixin Mini Program often finds it difficult to determine why it was triggered, making it difficult to make some responses to the routing rather than to the page.An example is when a Mini Program reloadsreLaunchrouting, the Mini Program may need to reset some of the global state to ensure that the subsequent logic works properly, or simulate a similar effect to a restart.However, to reverse the page life cyclereLaunchThis is difficult because even if all the current pages are destroyed at a certain moment, it is not necessarily caused byreLaunch(or redirecting when there is only a single page).redirectTo)。This set of interfaces can help with such scenarios.
# All listening and triggering sequences
| Page routing listening | Trigger timing | Number of triggers in each routing |
|---|---|---|
[wx.onBeforeAppRoute](<(wx.onBeforeAppRoute) >) | The routing event is sent to the repository and triggered before the repository executes the routing logic | first |
[wx.onAppRoute](<(wx.onAppRoute) >) | The routing event is sent to the repository, which is triggered after executing the routing logic | first |
[wx.onAppRouteDone](<(wx.onAppRouteDone) >) | Trigger the corresponding animation of the route (page push, roll, etc.) when it is completed | first |
[wx.onBeforePageLoad](<(wx.onBeforePageLoad) >) | Route-triggered pages are triggered before they are created | Unlimited |
[wx.onAfterPageLoad](<(wx.onAfterPageLoad) >) | Route-triggered page creation is triggered when the page is created | Unlimited |
[wx.onBeforePageUnload](<(wx.onBeforePageUnload) >) | Route-triggered pages are triggered before they are destroyed | Unlimited |
[wx.onAfterPageUnload](<(wx.onAfterPageUnload) >) | When the routing triggered page destruction is completed, it is triggered | Unlimited |
For example, in aredirectTo, the listening and processing logic will trigger in the following order:
- [
wx.onBeforeAppRoute](<(wx.onBeforeAppRoute) >) - [
wx.onBeforePageUnload](<(wx.onBeforePageUnload) >) - Former page
onUnloadLifecycle - The old page is destroyed, in the process of the page itself and all custom components in the page.
detachedLife cycle recursively triggered - The old page pops up the page stack and starts
getCurrentPagesThe interface can no longer fetch the old pages - [
wx.onAfterPageUnload](<(wx.onAfterPageUnload) >) - [
wx.onBeforePageLoad](<(wx.onBeforePageLoad) >) - Create a new page, during which the page itself and all the custom components in the page are
createdLife cycle recursively triggered - The new page is pushed into the page stack, and the
getCurrentPagesinterface can get the new page - Mount a new page, during which the page itself and all the custom components in the page are
attachedLife cycle recursively triggered - New page
onLoadLife cycle - New page
onShowLife cycle - [
wx.onAfterPageLoad](<(wx.onAfterPageLoad) >) - [
wx.onAppRoute](<(wx.onAppRoute) >) - (New page push animation finished) [
wx.onAppRouteDone](<(wx.onAppRouteDone) >)
For other routes, analogy can be made with the specific routing logic in page routing .
# Routing Event ID
To identify the same routing event during multiple listening callbacks, the framework generates a unique ID for each individual routing event in the Weixin Mini Program instance, called_routing event ID.In all page routing listeners, the event arguments carry a character stringrouteEventId, representing this routing event ID.The Mini Program can associate different callbacks triggered by the same route at different time nodes by reading therouteEventIdin the callback.For example:
const redirectToContext = {};
wx.onBeforeAppRoute(res => {
if (res.openType === "redirectTo") {
redirectToContext[res.routeEventId] = { startTime: new Date() };
}
});
wx.onBeforePageUnload(res => {
const context = redirectToContext[res.routeEventId];
if (context !== undefined) {
context.from = res.page.is;
context.data = res.page.data;
}
});
wx.onAfterPageLoad(res => {
const context = redirectToContext[res.routeEventId];
if (context !== undefined) {
console.log(
`A "redirectTo" route replaced page "${context.from}" to "${
res.page.is
}", which is started at ${context.startTime.toString()}`
);
res.page.setData(context.data);
delete redirectToContext[res.routeEventId];
}
});
In this example, we userouteEventIdA page creation and page destruction were associated once inredirectTo: data from the old page was logged when the page was destroyed and applied to the new page.
# Possible use cases
Conduct routing reports to restore user-use paths:
wx.onAppRoute(res => { myReportAppRoute(res.timeStamp, res.openType, res.path, res.query); });小程序冷启动或热启动时,重置所有状态:
wx.onBeforeAppRoute(res => { if (["appLaunch", "reLaunch", "autoReLaunch"].includes(res.openType)) { myGlobalState.reset(); } });这可以解决一些常见情景,例如小程序当前在后台,用户扫码热启动,触发
autoReLaunch时进行状态清理。新页面创建前先进行网络请求,使页面首屏创建和等待网络请求并行进行:
const pageRequestData = {}; wx.onBeforePageLoad(res => { pageRequestData[res.routeEventId] = new Promise((resolve, reject) => { wx.request({ url: `https://mysite.wechat.qq.com/page-data?path=${res.path}¶m=${res.query.param}`, success(res) { resolve(res); }, fail(res) { reject(res); } }); }); }); wx.onAfterPageLoad(res => { pageRequestData[res.routeEventId] .then(data => { res.page.setData(data); }) .catch(err => { console.error("page data init error", err); }); });当页面比较复杂时,页面创建需要一定时间。这个做法能充分利用页面的创建时间来等待网络请求返回,从而更快地将业务数据应用到页面上,展示给用户。