繁体   English   中英

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

[英]How to loop through objects in JSX react

我有嵌套对象的数据,其中我正在获取我的需求数据,现在我想循环通过 object 并在 UI 上呈现,但我不知道如何做到这一点,因为 UI 完全动态地依赖于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"
}

把它做成数组我这样做

const finalData =Object.entries(countData);

现在我想循环这个

请检查我的代码沙箱以获取完整代码

在我的代码沙箱中,我使用 HTML 进行静态渲染

大多数 React 应用程序将使用数据来呈现 UI。 这就是 React 擅长的地方。

第 1 步:创建可重用组件

你必须创建一个 React 组件来接收每个月的道具。 total_employeesarivingexitingcurrent_month )并正确呈现它们。

例如:

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>
  );
};

第 2 步:循环数据并渲染可重用组件

现在在您的父组件中,您可以遍历您的数据数组。

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]} />
    ))
  );
};

注意:传播...countData[month]是一个速记属性,用于将countData[month] [month] 的每个键值对作为道具传递。 我也可以写:

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

你可以在你的 JSX 代码中做这样的事情:

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

有很多代码重复,我们希望减少它(DRY 原则)。 首先,找到抽象描述您的 UI 的通用代码,即具有月/年 label、一些到达/退出字段和标签以及员工人数的组件。 将您想要显示的内容转换为采用这些“标准化”道具的组件。

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>
);

我不认为我会使用 map 这些,因为您之前和当前月份的标签不同,而且您一次只能显示 2 个月。 只需从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>
);

您可以使用:

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

首先,您需要将countData转换为可以运行循环的适当结构。 为此,您需要将其转换为数组的方式更改为以下

const finalData = Object.values(countData)

这样做之后,我们现在可以像这样使用map function 循环finalData变量。

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

此外,要处理 object 中缺少的键/值,您可以执行以下操作

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

希望这可以帮助

暂无
暂无

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

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