博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

ant design charts 获取后端接口数据展示

Posted on 2022-05-25 10:25  yqphare  阅读(465)  评论(0编辑  收藏  举报

今天在做项目的时候遇到几个让我很头疼的问题,一个是通过后端接口成功访问并又返回数据,但拿不到数据值。其二是直接修改state中的data,console中数组发生变化但任然数据未显示。

import React, { useState, useEffect } from 'react';
import { Line } from '@ant-design/plots';
import { PageContainer } from '@ant-design/pro-layout';
import ProForm, { ProFormDateRangePicker } from '@ant-design/pro-form';
import queryString from 'qs';


const DemoLine = () => {
const [data, setData] = useState([]);
useEffect(() => {
asyncFetch();
}, []);
var obj=[]
var pre=[]
const asyncFetch = () => {
fetch('/api/v1.0/inquireRepairsAnalysisNumberListTenant.json',{
method: 'POST',
body:new URLSearchParams(queryString.stringify({
sessionUuid: window.localStorage.getItem('sid') ,
startDate: '2021-12-01',
endDate: '2022-05-30',
}, { indices: false }))
})
.then(response=>response.json())//将respose转成json格式数据以便可以访问读取
.then(response=>{
obj=response.datas[0];//获取json数据中的data部分,并对其开始进行处理
console.log(obj)

for(var i = 0; i < obj.typeNameList.length;i++){
for(var j=0;j<obj.monthList.length-1;j++){


pre.push({ monthList:obj.monthList[j],
monthNumberList:obj.monthNumberList[j].numberList[i],
typeNameList:obj.typeNameList[i],
})
}
}
setData(pre)
}
)
.catch((error) => {
console.log('fetch data failed', error);
});
};


console.log(data,data.length)
const config = {
data,
xField: 'monthList',
yField: 'monthNumberList',
seriesField: 'typeNameList',
yAxis: {

},
legend: {
position: 'top',
},
smooth: true,
// @TODO 后续会换一种动画方式
animation: {
appear: {
animation: 'path-in',
duration: 5000,
},
},
};

return (
<PageContainer>
<ProForm
initialValues={{
dateRange: [Date.now(), Date.now() - 1000 * 60 * 60 * 24],
}}
>
<ProForm.Group title="日期区间选择">
<ProFormDateRangePicker name="dateRange" />
</ProForm.Group>
</ProForm>
<Line {...config} />
</PageContainer>
)
};

export default DemoLine;

 


通过接口获取到数据后,一直为response形式,处理很久,最后通过 .then(response=>response.json())//将respose转成json格式,但我们任然取不到PromiseResult中的内容,需要再次通过then方法

 

 

此时数据为json格式,为了取到json中的datas还需再 obj=response.datas[0];//获取json数据中的data部分,并对其开始进行处理

.then(response=>{
obj=response.datas[0];//获取json数据中的data部分,并对其开始进行处理
console.log(obj,'obj')

 


我们将取到的数据存在obj数组中

 

之后再对数据进行操作,由于我这边的用的多折线图,ant design charts中 他所需要的数据格式是数组内以对象的形式放单个数据,如图

 

 

所以我们需要对取到的obj数据数据进行处理,转换为对应的数据形式。pre为暂存数据数组。

for(var i = 0; i < obj.typeNameList.length;i++){
for(var j=0;j<obj.monthList.length-1;j++){


pre.push({ monthList:obj.monthList[j],
monthNumberList:obj.monthNumberList[j].numberList[i],
typeNameList:obj.typeNameList[i],
})
}
}

 


将我们的数据转换后通过usestate修改到data中

setData(pre)

 


 

通过设置折线图的对应属性

const config = {
data,//简写data:data
xField: 'monthList',
yField: 'monthNumberList',
seriesField: 'typeNameList',
yAxis: {

},
legend: {
position: 'top',
},
smooth: true,
// @TODO 后续会换一种动画方式
animation: {
appear: {
animation: 'path-in',
duration: 5000,
},
},
};

 


最终效果