gpt4 book ai didi

javascript - 如何在 JSX React 中循环对象

转载 作者:行者123 更新时间:2023-12-03 13:41:19 25 4
gpt4 key购买 nike

我有嵌套对象的数据,其中我正在获取我的要求的数据,现在我想循环该对象并在 UI 上渲染,但我不知道如何做到这一点,因为 UI 完全动态依赖于数据

我的数据

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

现在我想循环播放

please check my code-sandbox for full code

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

最佳答案

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

第 1 步:创建可重用组件

您必须创建一个 React 组件来接收每个月的 props。(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] 的每个键值对作为 prop 传递。我也可以这样写:

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

关于javascript - 如何在 JSX React 中循环对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61074719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com