[英]How to dynamically order my react components according to the order I get from my request?
I would like to transfer the responsibility of the order of my components to be passed to the.JSON file I GET from my request.我想将我的组件顺序的责任转移到我从我的请求中获取的.JSON 文件中。 In the following component, I get a list of 2 components with names
Component1
and Component2
and their data component1_data
and component2_data
accordingly.在以下组件中,我得到了 2 个组件的列表,名称分别为
Component1
和Component2
以及它们的数据component1_data
和component2_data
。 How can I put my components in the same order that they are on this list?我怎样才能将我的组件按照它们在此列表中的顺序排列?
Also, there is an if-else statement which is pushing the relevant content to the appropriate list.此外,还有一个 if-else 语句将相关内容推送到适当的列表中。 How can I write this more efficient so I will remove the repetition?
我怎样才能更有效地写这个,所以我会删除重复?
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"
}
]
Here's a basic rundown on a better way of doing it: map your data into the components that you want to render.以下是关于更好的方法的基本概要: map 将您的数据放入您要渲染的组件中。 Then you can output that directly in the JSX.
然后你可以直接在 JSX 中 output 那个。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.