首页 > 解决方案 > 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' });

但是,它不再起作用。

标签: reactjsreact-hooksreact-routerreact-router-dom

解决方案


看起来当前的 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');

推荐阅读