gpt4 book ai didi

reactjs - 在 react-router-dom v6 中配置路由

转载 作者:行者123 更新时间:2023-12-05 03:24:50 24 4
gpt4 key购买 nike

我正在使用带有 typescript 的 react-router-dom。我创建了一个配置文件,如下所示:

export interface RouteComponent {
path?: string;
element?: React.ComponentType<any>;
children?: RouteComponent[];
}

const routes: RouteComponent[] = [
{
element: MenuLayout,
children: [
{
path: "corp-list",
element: CorpList,
},
{
path: "/corp-list/:id",
element: DetailCorp,
},
],
},
{
children: [
{
path: "auth/login",
element: Login,
},
{
path: "auth/signup",
element: Login,
},
],
},
];

然后,我将其映射到 App.tsx 文件中的渲染路径

{routes.map((route, index) => (
<Route
path={route.path as string}
element={route.element}
/>
))}

它显示了 element 类型的错误在 Route 组件中使用 ReactNode 类型的子节点,而不是上面的 React.Component。但是当我尝试声明 element在具有 ReactNode 类型的配置路由中,例如:

{ path: "corp-list", element: <CorpList /> },

它大喊“CorpList 指的是一个值,但在这里被用作一个类型”。

那么,如何解决呢?而且,你如何在 react-router-dom v6 中配置路由,有什么建议吗?

最佳答案

如果您正在创建路由配置,则使用类型 react-router-dom导出,RouteObject在这种情况下。

RouteObject

/**
* A route object represents a logical route, with (optionally) its child
* routes organized in a tree-like structure.
*/
export interface RouteObject {
caseSensitive?: boolean;
children?: RouteObject[];
element?: React.ReactNode;
index?: boolean;
path?: string;
}

与类型声明的主要区别在于 elementReact.ReactNodechildrenRouteObject 的数组.

进口RouteObject并在您的配置中传递 element值作为 JSX。

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

const routesConfig: RouteObject[] = [
{
element: <MenuLayout />,
children: [
{
path: "corp-list",
element: <CorpList />
},
{
path: "corp-list/:id",
element: <DetailCorp />
}
]
},
{
children: [
{
path: "auth/login",
element: <Login />
},
{
path: "auth/signup",
element: <Login />
}
]
}
];

不要重新发明轮子,react-router-dom导出一个钩子(Hook)来使用路由配置对象并返回匹配的元素或 null。

useRoutes

The useRoutes hook is the functional equivalent of <Routes>, but ituses JavaScript objects instead of <Route> elements to define yourroutes. These objects have the same properties as normal <Route>elements, but they don't require JSX.

The return value of useRoutes is either a valid React element you canuse to render the route tree, or null if nothing matched.

import { useRoutes } from 'react-router-dom';

...

const routes = useRoutes(routesConfig);

return (
... nav bar ...
{routes}
...
);

Edit config-route-in-react-router-dom-v6

关于reactjs - 在 react-router-dom v6 中配置路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72198467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com