【问题标题】:Error using map to create Routes dinamically使用地图动态创建路由时出错
【发布时间】:2020-05-28 05:32:09
【问题描述】:

当我尝试从数组中动态使用 Route 时出现错误。

警告:使用了不正确的大小写。对 React 组件使用 PascalCase,对 HTML 元素使用小写。

这是我正在使用的元素:

const steps = [
  {
    name: 'Step Name',
    description: 'Step description (can be empty)',
    link: '/',
    component: 'Welcome'
  },
  {
    name: 'Step Name 2',
    description: 'Step Description',
    link: '/step-2',
    component: 'Step2'
  }
];

<Switch>
  {steps.map((step, index) => {
    return <Route exact path={step.link} key={index} component={step.component} />;
  })}
</Switch>

我尝试过使用模板文字,但又遇到了另一个错误:

Overload 1 of 2, '(props: Readonly): Route',给出了以下错误。 类型 'string' 不可分配给类型 'ComponentClass |功能组件 |组件类,任意> |函数组件<...> |未定义'。

【问题讨论】:

  • 你给 component 属性一个字符串,而不是一个组件。
  • 您必须使用component: Welcome 之类的东西,其中组件被导入为Wecome。但是只是一个字符串“Welcome”并没有办法知道它应该被视为一个组件。

标签: arrays reactjs typescript react-router


【解决方案1】:

正如@Brian 所说,您在映射时使用的是字符串而不是组件。导入组件并使用它而不是字符串。注意组件字段的值中没有引号。

import Welcome from '/path/to/welcome';
import Step2 from '/path/to/step2';
const steps = [
  {
    name: 'Step Name',
    description: 'Step description (can be empty)',
    link: '/',
    component: Welcome
  },
  {
    name: 'Step Name 2',
    description: 'Step Description',
    link: '/step-2',
    component: Step2
  }
];

【讨论】:

    猜你喜欢
    • 2018-09-07
    • 2022-01-04
    • 2023-04-11
    • 2018-09-19
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多