如何等待数据在useEffect钩子显示它之前?



所以我的问题很简单,我认为,但我真的不知道如何解决它。

我试图在ChartJS折线图中显示一组数据,但我在检索数据时遇到了问题。

下面是API调用的输出:
{
"total": 4294496256,
"valores": [
{
"time": "2022-06-01T07:00:00Z",
"value": 2535383574.2608695
},
{
"time": "2022-06-01T07:15:00Z",
"value": 2544284512.711111
},
{
"time": "2022-06-01T07:30:00Z",
"value": 2537325454.2222223
},
{
"time": "2022-06-01T07:45:00Z",
"value": 2543294555.022222
},
{
"time": "2022-06-01T08:00:00Z",
"value": 2543005058.8444443
},
{
"time": "2022-06-01T08:15:00Z",
"value": 2548481774.9333334
},
{
"time": "2022-06-01T08:30:00Z",
"value": 2544248149.3333335
},
{
"time": "2022-06-01T08:45:00Z",
"value": 2543528618.6666665
},
{
"time": "2022-06-01T08:56:06.1293542Z",
"value": 2541892416
}
]
}

我检索总价值以设置y轴的最大值,并且我需要循环遍历所有的"值"。并将它们压入数组

下面是useEffect调用的代码:
useEffect(() => {
const getData = async () => {
const res = await axios.get(
"http://192.168.10.88:3000/test/memory?intervalo=1h&servidor=192.168.2.138&filtro=-1h"
);
const gbMaximo = Number(res.data.total / 1000 / 1000 / 1000);
setMaximo(gbMaximo);
let ejex = [];
let valores = [];
res.data.valores.map((valor) => {
const tiempoFormateado = new Date(valor.time).toLocaleTimeString();
ejex.push(tiempoFormateado);
const gb = Number(valor.value) / 1000 / 1000 / 1000;
const gbFinal = gb.toFixed(2);
valores.push(gbFinal);
});
setLabels(ejex);
setDatasets(valores);
};
getData()
}, []);

其他一切都很好,但当我试图去网站,我只能看到2或3个值。

我的猜测是useEffect没有等待函数getData完成,但我真的不知道如何修复它,因为我不能让useEffect钩子运行一个异步函数。

谢谢你的帮助!

试试这个:

useEffect(() => {
const fetchData = async () => {
const res = await axios.get(
"http://192.168.10.88:3000/test/memory?intervalo=1h&servidor=192.168.2.138&filtro=-1h"
);
return res;
}
const getData = async () => {
let res = await fetchData();
const gbMaximo = Number(res.data.total / 1000 / 1000 / 1000);
setMaximo(gbMaximo);
let ejex = [];
let valores = [];
res.data.valores.map((valor) => {
const tiempoFormateado = new Date(valor.time).toLocaleTimeString();
ejex.push(tiempoFormateado);
const gb = Number(valor.value) / 1000 / 1000 / 1000;
const gbFinal = gb.toFixed(2);
valores.push(gbFinal);
});
setLabels(ejex);
setDatasets(valores);
};
getData()
}, []);

当然,你可以在useEffect

之外定义函数

最新更新