javascript - 如何在 JSX React 中循环遍历对象
问题描述
我有嵌套对象的数据,其中我正在获取我的需求数据,现在我想遍历该对象并在 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_employees
、ariving
和)exiting
并current_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]} />
))
);
};
注意:Spreading over...countData[month]
是一种速记属性,用于将每个键值对countData[month]
作为道具传递。我也可以写:
<MonthComponent
total_employees={countData[month].total_employees}
arrived={countData[month].arrived}
exited={countData[month].exited}
previous_month={countData[month].previous_month}
/>