【问题标题】:React Router v6 `useRouter` Hook with `basename` and RedirectionReact Router v6 `useRouter` Hook with `basename` 和 Redirection
【发布时间】:2023-03-26 10:12:01
【问题描述】:

以下代码 sn-p 解释了我如何定义应用程序路由。

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' });

但是,它不再起作用了。

【问题讨论】:

    标签: reactjs react-hooks react-router react-router-dom


    【解决方案1】:

    看起来当前的 API 还是很相似的。

    useRoutes

    类型声明

    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');
    

    【讨论】:

      猜你喜欢
      • 2022-12-10
      • 2022-01-21
      • 2018-05-14
      • 2022-01-17
      • 2023-01-17
      • 2022-01-11
      • 2022-01-24
      • 1970-01-01
      • 2022-06-18
      相关资源
      最近更新 更多