我想将组件顺序的责任转移到我从请求中获取的 .JSON 文件。在下面的组件中,我得到了 2 个组件的列表,其名称为 Component1
和 Component2
及其数据 component1_data
和 component2_data
相应地。如何按照列表中的顺序放置我的组件?
此外,还有一个 if-else 语句,它将相关内容推送到适当的列表。我如何才能更有效地编写此内容以便消除重复?
import React from 'react';
import Component1 from '../component1';
import Component2 from '../component2';
const Landing = (props) => {
const component1_data = [];
const component2_data = [];
if (data) {
for (let i = 0; i < data.length; i++) {
if (data[i].component_type === 'component1') {
const contentElement = data[i];
component1_data.push({ ...contentElement, content: props.data[contentElement.content] });
} else if (data[i].component_type === 'component2') {
const contentElement = data[i];
component2_data.push({ ...contentElement, content: props.data[contentElement.content] });
}
}
}
return (
<div>
<Component1 data={component1_data} />
<Component2 data={component2_data} />
</div>
);
}
export default Landing;
"landing": [
{
"component_type": "component2",
"content": "component2"
},
{
"component_type": "component1",
"content": "component1"
}
]
最佳答案
以下是更好的实现方法的基本概述:将数据映射到要渲染的组件中。然后你可以直接在 JSX 中输出。
import React from 'react';
import Component1 from '../component1';
import Component2 from '../component2';
// This is a mapping between the contentElement strings to the Component you want to render
const componentMap = {
component1: Component1,
component2: Component2,
};
const Landing = (props) => {
const components = data.map((datum) => {
const ComponentType = componentMap[datum.contentElement];
if(!ComponentType) return null;
// This returns the component you want with the data
// If the props aren't set up how you want, you should be able to modify it to have the right names
return (
<ComponentType data={{ ...datum, content: props.data[datum.content] }} />
);
});
return <div>{components}</div>;
};
export default Landing;
关于javascript - 如何根据我从请求中获得的顺序动态排序我的 react 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61914173/