在实际应用中,很多时候组件时嵌套关系,而react中组件中取数据只能取一层,但要定义多个数组对象又显得比较麻烦,后端可能为此多写几个接口。因此,在搭好组件框架后,我们可以先定义好数据结构,多层包裹数组对象,这样后端按我们定义好的数据结构写一个接口即可。
以两层为例,代码如下(示例):
//内层(第一层)的类型
type Jobinfo = {
JobType: string;
JobStatus: string;
JobTime: number;
JobDate: string;
FieldName: string;
JobArea: number;
};
//内层的数据,这里直接写死了,当然也可以传值
const [jobrecord, setjobrecord] = useState<Jobinfo[]>([
{
JobType: '旋耕',
JobStatus: '作业中',
JobTime: 10,
JobArea: 0,
JobDate: '9.07.15:00-9.10.19:00',
FieldName: '地块18-1'
},
{
JobType: '深翻',
JobStatus: '已完成',
JobTime: 10,
JobArea: 10,
JobDate: '9.07.15:00-9.10.19:00',
FieldName: '地块18-1'
},
{
JobType: '除草',
JobStatus: '已完成',
JobTime: 8,
JobArea: 10,
JobDate: '9.07.15:00-9.10.19:00',
FieldName: '地块18-1'
},
{
JobType: '旋耕',
JobStatus: '作业中',
JobTime: 10,
JobArea: 0,
JobDate: '9.07.15:00-9.10.19:00',
FieldName: '地块18-1'
}
]);
//外层(第二层)的类型
type AgriculturalRecord = {
AgriculturalName: string;
AgriculturalOil: number;
//此处类型为Jobinfo[]
AgriculturalJobinfo: Jobinfo[];
};
//外层的数据,同样可以传值
const [AgriculturalInfoRecord, setAgriculturalInfoRecord] = useState<AgriculturalRecord[]>([
{
AgriculturalName: '1号拖拉机',
AgriculturalOil: 50,
//此处数据为第一层的jobrecord
AgriculturalJobinfo: jobrecord
}
]);
如何传值,以第一层进行举例,三种方式,第三种后面补充再:
//假设feas为地图要素,其中包括这些属性数据,直接取
let jobrecordlist = [];
jobrecordlist.push({
//1、直接赋值
JobType: '深翻',
JobStatus: '已完成',
JobTime: 10,
JobArea: 10,
JobDate: '9.07.15:00-9.10.19:00',
FieldName: '地块18-1'
//2、feas传值
JobType: feas[0].values_.Type,
JobStatus: feas[0].values_.Status,
JobTime:feas[0].values_.Time,
JobArea: Number(feas[0].values_.Area.toFixed(2)),
JobDate: feas[0].values_.Date,
FieldName: feas[0].values_.Name,
});
setjobrecord(jobrecordlist);
代码如下(示例):
<div className="agricultural-info-div" ref={overlayContainerRef1}>
//外层循环遍历
{AgriculturalInfoRecord.map((ele, index) => {
return (
<div key={index}>
<div className="agricultural-info-lh">{ele.AgriculturalName}</div>
<div className="agricultural-info-top-righttitle">{ele.AgriculturalOil}</div>
//内层循环遍历
<div className="agricultural-info-mid-content">
{ele.AgriculturalJobinfo.map((ele, index) => {
return (
<div key={index} className="agricultural-info-mid-content1">
<div className="agricultural-info-c1">{ele.JobType}</div>
<div className="agricultural-info-c2">{ele.FieldName}</div>
...
</div>
</div>