在我的 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
出现此错误?修复它的最佳方法是什么?
答案 0 :(得分:1)
兄弟,试试这个。希望这会有所帮助。
const { id, component: Component } = step;
return <Component {...props} steps={steps} />;
问题是您正在 steps
数组中搜索与“id”匹配的索引。但是数组具有类似步骤 [0] 的数字类型索引。但这里的 id
是一个字符串。
答案 1 :(得分:1)
Steps
是一个数组,因此您需要像下面这样过滤组件:-
const Component = steps.find(innerStep => innerStep.id === id).component;