reactjs - React Router v6 `useRouter` Hook with `basename` 和 Redirection
问题描述
以下代码片段解释了我如何定义应用程序路由。
let routes = useRoutes([
{ path: '/', element: <Home /> },
{
path: 'users',
element: <Users />,
children: [
{ path: '/', element: <UsersIndex /> },
{ path: ':id', element: <UserProfile /> },
{ path: 'me', element: <OwnUserProfile /> },
]
}
]);
我想basename
为所有可用的路线定义一个。因此,每条路由都需要在/ui/
前面加上 basename。'/'
也应该重定向到'/ui/'
.
以前,在 beta 阶段,可以将 basename 定义如下:
const routes = useRoutes(appRoutes, { basename: 'ui' });
但是,它不再起作用。
解决方案
看起来当前的 API 仍然非常相似。
类型声明
declare function useRoutes( routes: RouteObject[], location?: Partial<Location> | string; ): React.ReactElement | null;
它仍然需要一个字符串基本位置,但现在它不是一个“配置”对象,而是直接一个Location
或一个字符串。
作为参考,这是Location
类型声明:
interface Location<S extends State = State> { pathname: string; search: string; hash: string; state: S; key: string; }
因此,您似乎可以使用部分位置并指定pathname
属性,也可以使用字符串。
const routes = useRoutes(appRoutes, { pathname: 'ui' });
const routes = useRoutes(appRoutes, 'ui');
推荐阅读
- pyspark - PySpark 类型错误
- c# - 为什么缩放为空?
- python - Python CSV:无法上传文件。索引错误(“字符串索引超出范围”)
- matplotlib - 如何避免在 matplotlib.pyplot.plotfile 中的非连续数据之间画线
- javascript - 通过 innerHTML 和 document.createElement 创建 HTML 有什么区别?
- listview - 是否可以使用 flutter_share 或其他共享插件从 Flutter image_picker 共享文本和照片?
- javascript - 如何加载身份验证?
- jenkins - 詹金斯 - 禁用单阶段的停止/取消
- django - 如何在创建提交的模型时修改我的 Django REST 端点以自动创建依赖模型?
- git - Git钩子检测获取的repo是否包含文件并停止合并