TypeError: Cannot read property 'component' based on id

TypeError: Cannot read property 'component' based on id

在我的 React 应用中,我想根据 id 渲染不同的组件。目前,我正在使用开关盒来执行此操作。但是,我想根据正在呈现的组件将不同的字符串传递到 header 中。我在 App.js

中创建了这样的步骤 object

** 显示错误的示例**:

https://stackblitz.com/edit/react-otwg1l

function App() {
    const [intialized, setInitialized] = useState(false);
  
    const steps = [
      {
        id: 'location',
        title: 'Select your store',
        nextStep: 'step 2',
        component: Comp1,
      },
      {
        id: 'questions',
        title: 'Answer Question',
        nextStep: 'step 3',
        component: Comp2,
      },
      {
        id: 'appointment',
        title: 'make and appointment',
        nextStep: 'step 4',
        component: Comp3,
      },
      {
        id: 'inputData',
        title: 'Add Data',
        nextStep: 'step 5',
        component: Comp4,
      },
      {
        id: 'summary',
        title: 'The End',
        nextStep: 'summary',
        component: Comp5,
      },
    ];
  
  
    return (
      <>
        <ThemeProvider theme={theme}>
          <SiteHeader />
          <div className="container">
            <ApptHeader steps={steps} />
            <Step steps={steps} />
          </div>
        </ThemeProvider>
      </>
    );
  }
  
  export default withRouter(App);

然后我将 steps 传递到我的 Step.js 组件

import React from 'react'

import { useStep } from 'react-hooks-helper';

const Step = ({ steps }) => {
  const { step, navigation } = useStep({ initialStep: 0, steps });
  const { id } = step;
  const props = { navigation };

  const Component = steps[id].component;
  return <Component {...props} steps={steps} />;
};

export default Step;

但是,当我尝试这样做时,出现以下错误:

TypeError: Cannot read property 'component' of undefined 这行代码:const Component = steps[id].component;

在 AppJS 中,控制台记录步骤 returns 以下信息:

(5) [{…}, {…}, {…}, {…}, {…}]
0: {id: "location", title: "Select your store", nextStep: "step 2", component: ƒ}
1: {id: "questions", title: "Answer Question", nextStep: "step 3", component: ƒ}
2: {id: "appointment", title: "make and appointment", nextStep: "step 4", component: ƒ}
3: {id: "inputData", title: "Add Data", nextStep: "step 5", component: ƒ}
4: {id: "summary", title: "The End", nextStep: "summary", component: ƒ}

但是,在步骤组件中,步骤控制台日志是 undefined,因为该组件未呈现。 id 导致此错误的原因是什么?修复它的最佳方法是什么?

兄弟,试试这个。希望这会有所帮助。

const { id, component: Component } = step;

return <Component {...props} steps={steps} />;

问题是您正在 steps 数组中搜索与 'id' 匹配的索引。但是数组有像 steps[0] 这样的数字类型索引。但是这里 id 是一个字符串。

Steps 是一个数组,因此您需要像下面这样过滤组件:-

const Component = steps.find(innerStep => innerStep.id === id).component;