使用React Router Config(https://github.com/ReactTraining/react-router/tree/master/packages/react-router-config),我有以下路由配置文件:
export const routes: RouteConfig[] = [
{
component: injectRoutes(HomeLayout),
path: "/home/(componentx|componenty)",
routes: [
{
component: ComponentX,
exact: true,
path: "/home/componentx",
},
{
component: ComponentY,
exact: true,
path: "/home/componenty",
},
],
},
];
我的injectRoutes
函数是用于构造子路由的HOC,看起来像这样:
import React from "react";
import { renderRoutes, RouteConfigComponentProps } from "react-router-config";
export const injectRoutes = (WrappedComponent: React.ComponentType<any>) => ({
route: { routes },
...props
}: RouteConfigComponentProps) => (
<WrappedComponent {...props}>{renderRoutes(routes)}</WrappedComponent>
);
鉴于上面的代码,我从打字稿中收到一个Property 'routes' does not exist on type 'RouteConfig | undefined'.ts(2339)
错误。
作为参考,以下是react-router-confiq
import * as React from "react";
import { RouteComponentProps, SwitchProps, match } from "react-router";
import { Location } from "history";
export interface RouteConfigComponentProps<Params extends { [K in keyof Params]?: string } = {}> extends RouteComponentProps<Params> {
route?: RouteConfig;
}
export interface RouteConfig {
key?: React.Key;
location?: Location;
component?: React.ComponentType<RouteConfigComponentProps<any>> | React.ComponentType;
path?: string | string[];
exact?: boolean;
strict?: boolean;
routes?: RouteConfig[];
render?: (props: RouteConfigComponentProps<any>) => React.ReactNode;
[propName: string]: any;
}
export interface MatchedRoute<Params extends { [K in keyof Params]?: string }> {
route: RouteConfig;
match: match<Params>;
}
export function matchRoutes<Params extends { [K in keyof Params]?: string }>(routes: RouteConfig[], pathname: string): Array<MatchedRoute<Params>>;
export function renderRoutes(
routes: RouteConfig[] | undefined,
extraProps?: any,
switchProps?: SwitchProps,
): JSX.Element;
我对React中的Typescript有点陌生,所以我不确定如何解决这个问题,因为据我所知,routes
是在RouteConfig
上定义的。错误是因为route
可能未定义?