将自定义道具与RouteComponentProps结合使用时,缺少位置,历史和匹配属性

时间:2019-06-03 19:19:34

标签: reactjs typescript react-router react-router-v4

我有一个处理路由的组件,并且我正在使用react-router属性:“历史,匹配,位置”。我将功能组件映射为接收IRoute作为道具,并将其与RouteComponentProps组合在一起,以便可以访问“历史记录,匹配​​项,位置”;

const PrivateRoute: FC<IRoute & RouteComponentProps> = ({ component: Component, roles, isAuthenticated, user, ...rest }) => (

);

这是我的路线代码。

const routes: IRoute[] = [
{
    path     : '/',
    exact    : true,
    auth     : false,
    component: Home
},
]

这是我的界面代码。

 export interface IRoute extends RouteComponentProps {
path     : string;
exact    : boolean;
auth     : boolean;
component: React.ElementType;
roles   ?: string[];
 }

当尝试初始化我的PrivateRoute组件时,我进入了终端:

TS2739: Type '{ path: string; exact: boolean; auth: boolean; component: ElementType<any>; roles?: string[] | undefined; key: number; }' is missing the following properties from type 'Readonly<Pick<IRoute & IAuthState & RouteComponentProps<{}, StaticContext, any>, "path" | "location" | "history" | "match" | "staticContext" | "component" | "exact" | "auth" | "roles">>': location, history, match

我是打字机的新手,所以如果有人可以向我解释我做错了什么,将不胜感激。谢谢您的时间!

1 个答案:

答案 0 :(得分:0)

这可能是这个问题的重复:enter image description here

由于简单的模拟方法,我最喜欢这个答案:How to test a React component with RouteComponentProps?

它展示了如何模拟 RouteComponentProps 并使用扩展运算符将其传递到您的组件中。

类似于:

const routeComponentPropsMock = {
  history: {} as any,
  location: {} as any,
  match: {} as any,
}

{ component: Component, roles, isAuthenticated, user, ...rest, ...routeComponentPropsMock  }