javascript - 如何根据我从请求中获得的顺序动态排序我的 react 组件?

标签 javascript reactjs

我想将组件顺序的责任转移到我从请求中获取的 .JSON 文件。在下面的组件中,我得到了 2 个组件的列表,其名称为 Component1Component2 及其数据 component1_datacomponent2_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/

相关文章:

javascript - 将 jQuery parseXml 限制为一定数量的循环

javascript - Nodejs在请求中数据处理完成后响应

javascript - 检查 sitecatalyst/Omniture s.t() 是否已被调用

reactjs - 为什么 useEffect 不能在 return 语句中访问我的状态变量?

javascript - 如何从图片中提取图标并显示在页面中? (通过 javascript 或 jquery 或 css)

reactjs - React - 转发多个引用

twitter-bootstrap - 是否可以根据需要设置react-day-picker的输入字段?

javascript - Wepack 错误 : Adjacent JSX elements must be wrapped in an enclosing tag

reactjs - ag-grid-react 无法正确渲染

javascript - 获取选择列表中最近添加/更改的项目(通过 jQuery 或 Angular JS)