reactjs - 在 React 和饼图中使用 setState 的多个获取请求
问题描述
我的查询执行时间超过 2 分钟,因此它在浏览器中超时。所以现在我打破了查询,现在作为一个单独的 API 运行,这很有帮助,但现在我不知道如何处理这三个请求,以便它可以呈现数据。
注意:API 的数据存储在 react 的 State 组件中,这里是“Data”。
现在我有一个逻辑,但任何人都可以给我一个如何实现它的方向。
逻辑:在将 API 的结果直接存入 state 组件之前,我们可以先将其存入不同的数组,然后我们可以遍历这个数组以供饼图使用,然后将这些数据存入 state 组件,用于渲染“渲染”功能中的饼图。
这里我同时进行三个不同的 API 调用并存储它,这里 API 的结果直接存储在状态组件中:
componentDidMount() {
Promise.all([
fetch("http://localhost:4000/api/EMEA/E_claimQuarter"),
fetch("http://localhost:4000/api/EMEA/E_claimQuarter1"),
fetch("http://localhost:4000/api/EMEA/E_claimQuarter2")
])
.then(([res1, res2, res3]) =>
Promise.all([res1.json(), res2.json(), res3.json()]))
.then(([data1, data2, data3]) =>
this.setState({
// Data: data1, data2, data3,
Data: {
labels: [
"FY19 Q1[NOV-JAN]",
"FY19 Q2[FEB-APR]",
"FY18 Q3[SEP-NOV]"
],
datasets: [
{
label: "",
data: data1,
backgroundColor: [
"rgba(255,105,145,0.6)",
"rgba(155,100,210,0.6)",
"rgb(63, 191, 191)"
]
}
]
}
})
);
}
这就是你如何处理数据表单 API 并循环遍历它,然后为各种图表呈现这些数据,在我的例子中是饼图:
ComponentDidMount() {
axios.get(`http://localhost:4000/api/APJ/A_claimQuarter`)
***************************************************************
.then(res => {
const claims = res.data;
let claim = [];
claims.forEach(element => {
claim.push(element.CNT1);
});
********************************************************************
this.setState({
Data: {
labels: ['FY19 Q1[NOV-JAN]','FY19 Q2[FEB-APR]','FY18[SEP-NOV]'],
datasets:[
{
label:'',
data: claim ,
backgroundColor:[
'rgba(255,105,145,0.6)',
'rgba(155,100,210,0.6)',
'rgb(63, 191, 191)'
]
}
]
}
});
})
}
解决方案
我做了一些修改,现在它对我来说工作正常,如果有人想要答案,你可以看看我的,它是 100% 工作的:
constructor(props) {
super(props);
this.state = {
Data: []
};
}
componentDidMount() {
Promise.all([
fetch("http://localhost:4000/api/EMEA/E_claimQuarter"),
fetch("http://localhost:4000/api/EMEA/E_claimQuarter1"),
fetch("http://localhost:4000/api/EMEA/E_claimQuarter2")
])
.then(([res1, res2, res3]) => Promise.all([res1.json(), res2.json(), res3.json()]))
.then(([data1, data2, data3]) =>
{
console.log(typeof(data1));
const array = [...data1, ...data2, ...data3];
// const A = JSON.strigify(array);
console.log('hi');
console.log(array);
console.log(data1);
// console.log(A);
let claim = [];
array.forEach(element => {
claim.push(element.COUNT);
});
console.log(claim);
this.setState({
// Data: data1, data2, data3,
Data: {
labels: [
"FY19 Q1[NOV-JAN]",
"FY19 Q2[FEB-APR]",
"FY18 Q3[SEP-NOV]"
],
datasets: [
{
label: "",
data: claim,
backgroundColor: [
"rgba(255,105,145,0.6)",
"rgba(155,100,210,0.6)",
"rgb(63, 191, 191)"
]
}
]
}
})
});
}
推荐阅读
- .net - 部署 Angular 应用程序和 .net core web api 的步骤
- python - Python ast(gast)模块 - 同一对象的多个副本
- javascript - 从代码隐藏调用javascript不起作用
- tensorflow - TensorFlow Probability 中联合分布的组成
- llvm - 优化生成超长函数定义
- c++ - 递归 C++ 函数未返回正确的布尔值
- decentralized-identity - 有人成功在测试中进行 DID 注册(去中心化身份 Microsoft SDK)吗?
- python - Pythod 中的字典定义存在语法错误
- javascript - 在javascript函数中调用额外的文本文档以正常代码工作
- node.js - MongoDB - 如何在集合中找到 10 个最大值