reactjs React typescript 工艺路线文件

dzjeubhm  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(155)

我想在React(typescript)版本中使用以下代码创建routes.ts文件(JS版本中的示例)

routes = [
  {
    path: 'app', component: isLoggedIn ? <HomeComponent /> : <Navigate to="/login" />, 
    children: [
      { path: '', component: <Navigate to="/dashboard" /> },
      { path: 'dashboard', component: <DashboardComponent /> },
      { path: 'other', component: <OtherComponent /> },
    ] 
  },
  { path: 'login', component: <LoginComponent />  },
  { path: 'register', component: <RegisterComponent />  },
  { path: '**', component: <NotFoundComponent />  },
]

App.tsx中应该是这样,JS版本的引用

return (
  <BrowserRouter>
    {routes.map(r => {
      ...//logic
    })}
  </BrowserRouter>
)

这是写在非常简短的只是为了解释的要求。PS:JS版本可以很好地处理这种逻辑,但是TS转换很困难,并且目前在文档和论坛中不可用

gjmwrych

gjmwrych1#

我建议不要使用自己的路径渲染逻辑,而是将routes配置对象转换为一种更容易使用react-router-dom的格式,不需要做太多更改,基本上只需将component属性的组件转换为element属性即可。

import { RouteObject } from "react-router-dom";

...

const routes: RouteObject[] = [
  {
    path: "app",
    element: isLoggedIn ? <HomeComponent /> : <Navigate to="/login" />,
    children: [
      { index: true, element: <Navigate to="dashboard" /> },
      { path: "dashboard", element: <DashboardComponent /> },
      { path: "other", element: <OtherComponent /> }
    ]
  },
  { path: "login", element: <LoginComponent /> },
  { path: "register", element: <RegisterComponent /> },
  { path: "*", element: <NotFoundComponent /> }
];

导入并使用createBrowserRouter(* 任何数据路由器,有关详细信息,请参见Picking a Router *)和RouterProvider

import {
  createBrowserRouter,
  RouterProvider,
  Navigate
} from "react-router-dom";

...

const router = createBrowserRouter(routes);

...

<RouterProvider router={router} />

typescript 演示

如果您还没有完全准备好跳转到数据路由器,那么请保留BrowserRouter,并使用useRoutes挂钩代替。

import {
  Navigate,
  RouteObject,
  useRoutes
} from "react-router-dom";

...

const routes: RouteObject[] = [
  { path: "/", element: <Navigate to="app" /> },
  {
    path: "app",
    element: isLoggedIn ? <HomeComponent /> : <Navigate to="/login" />,
    children: [
      { index: true, element: <Navigate to="dashboard" /> },
      { path: "dashboard", element: <DashboardComponent /> },
      { path: "other", element: <OtherComponent /> }
    ]
  },
  { path: "login", element: <LoginComponent /> },
  { path: "register", element: <RegisterComponent /> },
  { path: "*", element: <NotFoundComponent /> }
];

const appRoutes = useRoutes(routes);

...

return (
  ...
  {appRoutes}
  ...
);

相关问题