reactjs - 将自定义 Prop 与 RouteComponentProps 组合时缺少位置、

我有一个处理路由的组件,我正在使用 react-router 属性:'history, match, location'。我将我的功能组件映射为接收 IRoute 作为 props 并将其与 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

我是 typescript 的新手,所以如果有人能向我解释我做错了什么,我将不胜感激。感谢您的宝贵时间!

最佳答案

这可能是这个问题的重复:How to test a React component with RouteComponentProps?

由于简单的模拟方法,我最喜欢这个答案:https://stackoverflow.com/a/60765926/2212881

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

类似于:

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

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

关于reactjs - 将自定义 Prop 与 RouteComponentProps 组合时缺少位置、历史和匹配属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56433366/

相关文章:

python - 从 websocket 读取数据而不阻塞代码

junit - 覆盖本地函数中的 Mockito 语句不适用于 PER CLASS 模式?

azure-ad-b2c - Azure AD B2C 中的自定义策略不允许为属性保存空字符串

javascript - 如何在 Webpack 4 项目中导入自定义 UMD 模块

javascript - 如何通过html或javascript在chrome中打开翻译对话框

reactjs - JWT LocalStorage 与 Cookie

jupyter-notebook - `jupyter kernelspec list` 命令没有找

javascript - 代码输出一个数字而不是未定义的?

csv - 在 Java 中解析大型 CSV 文件的最快最有效的方法

ios - 在应用程序生命周期的中间将本地 Realm 转换为同步 Realm (在 Swift 中