简体   繁体   English

如何在 JSX React 中循环遍历对象

[英]How to loop through objects in JSX react

I have data of nested objects in which I am getting data of my requirement, Now I want to loop through that object and render on UI, But I am not getting Idea how to do that as the UI is fully Dynamically dependent on data .我有嵌套对象的数据,其中我正在获取我的需求数据,现在我想循环通过 object 并在 UI 上呈现,但我不知道如何做到这一点,因为 UI 完全动态地依赖于data

My data我的数据

const countData = {
  "current_month": {
    "total_employes": 6,
    "ariving": "+3",
    "exiting": "-1",
    "current_month": "April    2020",
    "__typename": "CurrentMonthTotalEmp"
  },
  "previous_month": {
    "total_employes": "3",
    "arrived": "+2",
    "exited": "-2",
    "previous_month": "March 2020",
    "__typename": "PrevMonthTotalEmp"
  },
  "__typename": "CurPrevMonthEmps"
}

to make it as array I doing this把它做成数组我这样做

const finalData =Object.entries(countData);

Now I want to loop this现在我想循环这个

please check my code-sandbox for full code请检查我的代码沙箱以获取完整代码

here in my code-sandbox I am rendering statically with HTML在我的代码沙箱中,我使用 HTML 进行静态渲染

Most of your React applications will use data to render a UI.大多数 React 应用程序将使用数据来呈现 UI。 That's what React excels in.这就是 React 擅长的地方。

Step 1: Create a reusable component第 1 步:创建可重用组件

You'll have to create a React component which receives the props for each month.你必须创建一个 React 组件来接收每个月的道具。 ( total_employees , ariving , exiting and current_month ) and renders them correctly. total_employeesarivingexitingcurrent_month )并正确呈现它们。

for example:例如:

const MonthComponent = ({ total_employees, ariving, exiting, current_month }) => {

  //above return you can alter your data however you want using normal javascript

  return (
    //in 'return' you can return HTML or JSX to render your component.
    <div>
      <p>{total_employees}</p>
      <p>{ariving}</p>
      <p>{exiting}</p>
      <p>{current_month}</p>
    </div>
  );
};

Step 2: Loop over your data and render your reusable component第 2 步:循环数据并渲染可重用组件

Now in your parent component you can loop over your array of data.现在在您的父组件中,您可以遍历您的数据数组。

const ParentComponent = () => {

  const countData = {
    "current_month": {
      "total_employes": 6,
      "ariving": "+3",
      "exiting": "-1",
      "current_month": "April    2020",
      "__typename": "CurrentMonthTotalEmp"
    },
    "previous_month": {
      "total_employes": "3",
      "arrived": "+2",
      "exited": "-2",
      "previous_month": "March 2020",
      "__typename": "PrevMonthTotalEmp"
    },
    "__typename": "CurPrevMonthEmps"
  }

  const months = Object.keys(countData); // ["current_month", "previous_month"]

  return (
    months.map(month => (
      // map over months and render your reusable component for each month
      <MonthComponent {...countData[month]} />
    ))
  );
};

Note: Spreading over ...countData[month] is a shorthand property to pass every key-value pair of countData[month] as a prop.注意:传播...countData[month]是一个速记属性,用于将countData[month] [month] 的每个键值对作为道具传递。 I could also have written:我也可以写:

<MonthComponent
  total_employees={countData[month].total_employees}
  arrived={countData[month].arrived}
  exited={countData[month].exited}
  previous_month={countData[month].previous_month}
/>

You can do something like this in your JSX code:你可以在你的 JSX 代码中做这样的事情:

{finalData.map(value => (
  <div>{value.something}</div>
))}

There is a lot of code duplication, we want to reduce that (DRY Principle).有很多代码重复,我们希望减少它(DRY 原则)。 First, find the common code that abstractly describes your UI, ie a component that has a month/year label, some arrive/exit fields & labels, and an employee count.首先,找到抽象描述您的 UI 的通用代码,即具有月/年 label、一些到达/退出字段和标签以及员工人数的组件。 Convert what you want displayed to a component that takes these "standardized" props.将您想要显示的内容转换为采用这些“标准化”道具的组件。

const MonthData = ({
  arrive,
  arriveLabel,
  exit,
  exitLabel,
  totalEmployees,
  month,
}) => (
  <Fragment>
    <label className="monthYr" align="left">
      {month}
    </label>
    <div className="row countDiv">
      <div className="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6 total">
        <label className="totalHeading">Total employees</label>
        <div className="totalCount">{totalEmployees}</div>
      </div>

      <div className="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6">
        <button className="btn btn-outline-secondary button_Count form-control">
          {arriveLabel}
          <span className="badge badge-pill badge-primary ml-2">
            {arrive}
          </span>
        </button>
        <button className="btn btn-outline-secondary form-control">
          {exitLabel}
          <span className="badge badge-pill badge-primary ml-2">
            {exit}
          </span>
        </button>
      </div>
    </div>
  </Fragment>
);

I don't think I'd map these as you have different labeling for previous vs. current months, and you only ever display 2 months at a time.我不认为我会使用 map 这些,因为您之前和当前月份的标签不同,而且您一次只能显示 2 个月。 Just destructure from the countData the two months' data.只需从countData中解构两个月的数据。

const { current_month, previous_month } = countData;

return (
  <div className="row container-fluid">
    <div className="form-control graphHeading"> Manpower Graph</div>
    <div className="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12">
      <div className="row widthContainer">
        <div className="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6">
          <MonthData
            arrive={previous_month.arrived}
            arriveLabel="arrived"
            exit={previous_month.exited}
            exitLabel="exited"
            month={previous_month.previous_month}
            totalEmployees={previous_month.total_employees}
          />
        </div>
        <div className="col-12 col-sm-12 col-md-6 col-lg-6 col-xl-6">
          <MonthData
            arrive={current_month.arriving}
            arriveLabel="arriving"
            exit={current_month.exiting}
            exitLabel="exiting"
            month={current_month.current_month}
            totalEmployees={current_month.total_employees}
          />
        </div>
      </div>
    </div>
  </div>
);

you can use:您可以使用:

{
    Object.keys(countData).map(key=>{
        const month = countData[key]
        return(
            //you have access to month
            <div>{month.total_employes}</div>
        );
    })
}

First, you need to convert the countData into a proper structure over which we can run our loop.首先,您需要将countData转换为可以运行循环的适当结构。 to do that you need to change how you convert it to array to the following为此,您需要将其转换为数组的方式更改为以下

const finalData = Object.values(countData)

After doing so we can now loop over the finalData variable using a map function like this.这样做之后,我们现在可以像这样使用map function 循环finalData变量。

{finalData.map(data => (
  <div>{data.total_employes}</div>
  <div>{data.ariving}</div>
))}

Moreover to handle missing key/values in the object you can do the following此外,要处理 object 中缺少的键/值,您可以执行以下操作

{finalData.map(data => (
  <div>{data.total_employes ? data.total_employes : 'NA'}</div>
  <div>{data.ariving ?  data.ariving : 'NA'}</div>
))}

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM