【问题标题】:Typescript with dynamic map router got type error带有动态地图路由器的打字稿出现类型错误
【发布时间】:2021-07-11 07:32:40
【问题描述】:

使用 Typescript 和 react-router-dom。我声明了一个数组以在Switch 中动态生成Route 子代。但是得到了类型错误:

Conversion of type '{ routeMap: RouteProps<string, { [x: string]: string | undefined; }>[]; "": any; }' to type 'Switch' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
  Type '{ routeMap: RouteProps<string, { [x: string]: string | undefined; }>[]; "": any; }' is missing the following properties from type 'Switch': context, setState, forceUpdate, render, and 3 more.

这是我的代码:

import { RouteProps, Switch, Redirect, Route } from 'react-router-dom'

export const routeMap: RouteProps[] = [
  {
    path: '/',
    exact: true,
    component: loadable(() => import('Views/Home')),
  },
  {
    path: `${base}`,
    exact: true,
    component: loadable(() => import('Views/Home')),
  },
  {
    path: `${base}/index`,
    component: loadable(() => import('Views/Home')),
  },
  {
    path: `${base}/404`,
    component: loadable(() => import('Views/404')),
  },
  {
    path: `${base}/floorConstruct`,
    component: loadable(() => import('Views/FloorConstruct')),
  },
  {
    path: `${base}/dataTracking`,
    component: loadable(() => import('Views/DataTracking')),
  },
  {
    path: `${base}/pageConfig`,
    component: loadable(() => import('Views/PageConfig')),
  },
]
export const StaticRouters = () => (
  <Switch>
    {routeMap.map((route, index) => (
      // eslint-disable-next-line react/no-array-index-key
      <Route key={index} {...route} />
    ))}
    <Redirect to={`${base}/404`} />
  </Switch>
)

我发现StaticRouter() =&gt; boolean ???

我已将部分代码上传到codesandbox

【问题讨论】:

  • JSX 代码需要在 .tsx 文件中(如果你问我,这很烦人,但它就是这样)

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


【解决方案1】:

我在 Visual Studio 中尝试了您的所有代码,但没有出现您的错误。

感谢您的代码框。

我尝试了一些代码,我找到了一个不会抛出错误但我不知道你的错误来自哪里的解决方案。

Here is my solution.

唯一不同的是loadable(() =&gt; import('Views/Home'))不能与“组件”道具的类型匹配React.ComponentType&lt;any&gt; | React.ComponentType&lt;RouteComponentProps&lt;any, StaticContext, unknown&gt;&gt; | undefined

【讨论】:

  • 谢谢。我已经在代码框中上传了一些代码并更新了我的问题。
  • 感谢您的帮助。你的解决方案正是我所做的:-)。
  • 原因可能是apokryfos 的评论。我尝试将 routes/index.ts 重命名为 routes/index.tsx,它可以工作。
猜你喜欢
  • 2022-10-13
  • 2017-10-30
  • 2016-08-08
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 2017-12-27
  • 2023-01-03
相关资源
最近更新 更多