首页 > 解决方案 > TypeError:无法根据 id 读取属性“组件”

问题描述

在我的 React 应用程序中,我想根据 id 呈现不同的组件。目前,我正在使用开关盒进行此操作。但是,我想根据正在呈现的组件将不同的字符串传递到标题中。我在 App.js 中创建了这样的步骤对象

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

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 中,步骤的控制台日志返回以下信息:

(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: ƒ}

但是,在 Step 组件中,steps 控制台日志是undefined因为该组件没有呈现。是什么导致了这个错误以及id修复它的最佳方法是什么?

标签: javascriptreactjsreact-hooksreact-hook-form

解决方案


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

const { id, component: Component } = step;

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

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


推荐阅读