我正在与React合作,我想在UI上显示一些动态内容,但是由于我是新手而无法循环数据,所以发现这样做很困难
state={
dashboardManpowerCount:{
"CurrentMonth": {
"Total No of employes": 25,
"Ariving": 10,
"Exited": 8
},
"PreviousMonth": {
"Total No of employes": 25,
"Ariving": 10,
"Exited": 8
}
}
}
class currAndprevMonthcCounts extends Component {
render(){
const {dashboardManpowerCount} = this.state
return(
<div>
<div className="col-6 col-sm-6 col-md-6 col-lg-3 col-xl-3">
<div className="row">
<div className="col-12 col-sm-12 col-md-6 col-lg-5 col-xl-5">
<h6>Previous Month</h6>
<h2>395</h2>
</div>
<div className="col-12 col-sm-12 col-md-6 col-lg-7 col-xl-7">
<span className="badge badge-pill badge-secondary mt-2"
>+7 Ariving</span>
<br></br>
<span className="badge badge-pill badge-secondary mt-3">-3 Exiting</span>
</div>
</div>
</div>
<div className="col-6 col-sm-6 col-md-6 col-lg-3 col-xl-3">
<div className="row">
<div className="col-12 col-sm-12 col-md-6 col-lg-5 col-xl-5">
<h6>Previous Month</h6>
<h2>395</h2>
</div>
<div className="col-12 col-sm-12 col-md-6 col-lg-7 col-xl-7">
<span className="badge badge-pill badge-secondary mt-2">+5 Ariving</span>
<br></br>
<span className="badge badge-pill badge-secondary mt-3">-3 Exiting</span>
</div>
</div>
</div>
</div>
)
}
}
我想遍历对象并在jsx中代替静态内容进行呈现,这两个选项分别是当月数据和上月数据
编辑/更新
我想我在这里缺少一些在UI This is what I am trying to get上使用静态数据的有效示例
答案 0 :(得分:2)
使用object.keys
或object.entries
遍历对象的属性。
render() {
const { dashboardManpowerCount } = this.state;
const dashboardManpowerCountArray = Object.entries(dashboardManpowerCount);
return (
<div>
{dashboardManpowerCountArray.map(arr => {
return (
<div key={arr[0]}>
<h3>{arr[0]}</h3>
{Object.entries(arr[1]).map(monthArr => {
return (
<span key={monthArr[0]} style={{ display: "block" }}>{`${
monthArr[0]
} ${monthArr[1]}`}</span>
);
})}
</div>
);
})}
</div>
);
}
请参见此stackblitz。显然,更改样式和标签的方式。
更新
这是您可以用来显示数据的jsx-
import React from "react";
import { render } from "react-dom";
import "bootstrap/dist/css/bootstrap.min.css";
class Events extends React.Component {
state = {
dashboardManpowerCount: {
CurrentMonth: {
"Total No of employes": 25,
Ariving: 10,
Exited: 8
},
PreviousMonth: {
"Total No of employes": 25,
Ariving: 10,
Exited: 8
}
}
};
render() {
return (
<div className="divParent row container">
{Object.entries(this.state.dashboardManpowerCount).map(
([monthName, monthData]) => {
return (
<div className="col-6 col-sm-6 col-md-6 col-lg-3 col-xl-3">
<div className="row">
<div className="col-12 col-sm-12 col-md-6 col-lg-5 col-xl-5">
<h6>{monthName}</h6>
<h2>{monthData["Total No of employes"]}</h2>
</div>
<div className="col-12 col-sm-12 col-md-6 col-lg-7 col-xl-7">
<span className="badge badge-pill badge-secondary mt-2">
{`+${monthData.Ariving} Ariving`}
</span>
<br />
<span className="badge badge-pill badge-secondary mt-3">
{`-${monthData.Ariving} Exiting`}
</span>
</div>
</div>
</div>
);
}
)}
</div>
);
}
}
render(<Events />, document.getElementById("root"));
但是这次组件不是完全动态的。如果将来您对象的架构发生更改,您也必须更改jsx。