跳到主要内容

useRouter

路由相关, 扩充 Taro useRouter , 并融合跳转小程序 api

何时使用

当需要获取路由,或者进行路由以及小程序跳转操作时

API

const [routerInfo, { navigate, switchTab, relaunch, redirect, back, exit }] =
useRouter<R>();

参数说明

返回值说明

返回值说明类型
routerInfo当前页面路由信息Route<R>
navigate打开到应用内的某个页面RouteNavigate<R>
switchTab异步跳转 tabBar 页面SwitchTab
relaunch异步关闭当前页面,跳转到应用内的某个页面RouteNavigate<R>
redirect异步保留当前页面,跳转到应用内的某个页面或跳转至小程序RouteNavigate<R>
back异步关闭当前页面,返回上一页面或多级页面或返回小程序Back
exit异步关闭小程序Exit

Route

type Route<R extends Partial<RecordData>> = RouterInfo<R> & {
from: ReturnType<typeof useFrom>;
};

RouteNavigate

type RouteNavigate<R> = PromiseParamsAction<RouteOption<R>>;

SwitchTab

type SwitchTab = PromiseAction<string>;

Back

type Back = PromiseParamsAction<RouteBackOption>;

Exit

type Exit = PromiseWithoutOptionAction;

代码演示

basic/useRouter/index
import React from 'react';
import { useRouter } from 'taro-hooks';
import DemoContent from '@src/components/DemoContent';
import { Button, Cell } from '@taroify/core';

export default () => {
const [routerInfo, { navigate, switchTab, relaunch, redirect, back, exit }] =
useRouter();

return (
<DemoContent>
<Cell
title="来源页面"
brief={JSON.stringify(routerInfo?.from?.route)}
></Cell>
<Button
block
color="primary"
className="gap"
onClick={() => switchTab('pages/about/index')}
shape="square"
>
跳转TabBar
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => relaunch('/pages/network/useRequest/index')}
shape="square"
>
重新打开一个页面
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => redirect('/pages/network/useOnline/index')}
shape="square"
>
重定向页面
</Button>
<Button
block
color="primary"
className="gap"
onClick={() =>
navigate('/pages/wechat/useLaunchOptions/index', {
from: 'useRouter',
})
}
shape="square"
>
跳转页面
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => back()}
shape="square"
>
返回上一页
</Button>
<Button
block
color="primary"
className="gap"
onClick={() =>
navigate(
'/pages/index/index',
{ appId: 'wxce815e33b0e06cf5', extraData: { from: 'taro-hooks' } },
true,
)
}
shape="square"
>
跳转小程序
</Button>
<Button
block
color="primary"
className="gap"
onClick={() =>
navigate(
'/pages/index/index',
{ appId: 'wxce815e33b0e06cf5', extraData: { from: 'taro-hooks' } },
true,
true,
)
}
shape="square"
>
半屏打开小程序
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => back({}, true)}
shape="square"
>
返回小程序
</Button>
<Button
block
color="primary"
className="gap"
onClick={() => exit()}
shape="square"
>
退出小程序
</Button>
<Cell title="当前页面" brief={JSON.stringify(routerInfo)}></Cell>
</DemoContent>
);
};

Hook 支持度

微信小程序H5ReactNative
✔️✔️✔️