javascript - 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
修复它的最佳方法是什么?
解决方案
兄弟,试试这个。希望这会有所帮助。
const { id, component: Component } = step;
return <Component {...props} steps={steps} />;
问题是您正在steps
数组中搜索与“id”匹配的索引。但是数组有像steps[0]这样的数字类型索引。但这里id
有一个字符串。
推荐阅读
- html - 如何让溢出在 CSS 网格中正常工作?
- node.js - 使用 systemctl 启动节点进程时如何加载 PATH 变量?
- ms-access - 控制查询字段的文本框
- c# - 有没有办法访问和更改以编程方式添加到面板的自定义控件中的值?
- openshift - Openshift 3.10 如何从现有对象创建模板
- servicestack - Servicestack 中的 FallbackRoute 问题
- python - 通过使用 pandas 提取和分组列来总结数据框
- linux - Selenium Webdriver Performance for Parallel testing with Chrome Driver on Windows 10 vs Ubuntu Linux and local vs cloud
- apache-nifi - NiFi从覆盖nifi.properties中的值
- postgresql - PostgreSQL 中具有大量分区的数据库的查询计划时间很长