在 React 中使用 API 数据创建 Chart.js

Creating Chart.js using API data in react

我是React新手,不太了解React hook是如何工作的,这里遇到一个问题。我尝试使用 Chart.js 绘制图表并使用 API 中的数据在特定间隔内重新绘制它,问题是图表不读取数据。这是获取数据函数:

const getData = async ()=>{
const response = await axiosJWT.get('http://localhost:5000/in-total-assets', {
  headers:{
    Authorization: `Bearer ${token}`
  }
})
var formated = [];
formated.push = response.data[0].Total_OR_Weight;
formated.push = response.data[0].Total_IN_Weight;
setData(formated)
}

这是图表渲染器函数:

async function getChart(){
await getData();
let config = {
  type: "doughnut",
  data: {
    labels: [
      "Organic",
      "Inorganic",
    ],
    datasets: [
      {
        label: 'Dataset',
        backgroundColor: ["#ed64a6", "#4c51bf"],
        data: data,
        hoverOffset: 5
      },
    ],
  }
};
let ctx = document.getElementById("doughnut-chart").getContext("2d");
window.myBar = new Chart(ctx, config);
}

这里是 useEffect 函数:

React.useEffect(() => {
refreshToken();
getChart();
const id = setInterval(getChart, 10000)
return ()=> clearInterval(id);
}, []);

结果是图表显示未定义为图表的值,知道如何解决吗?

您要绘制图表部分的 html 文件应如下所示:

<div class="canvasContainer" style="margin-top:20px; margin-bottom:20px;">
  <canvas id="doughnut-chart"></canvas>
</div>

我首先想到的是,如果有任何数据来自您的 getData 函数,如果数据正在流入,那么我的下一个猜测是 setData 在您决定在代码中使用变量数据时没有及时更新它。 我在 google 搜索

中找到了这个

State updates are asynchronous. This was true in class-based components. It's true with functions/Hooks

Even though they are asynchronous, the useState and setState functions do not return promises. Therefore we cannot attach a then handler to it or use async/await to get the updated state values

所以,这就是你的问题。您需要重新定义获取数据的部分和设置图表的部分,因为 await 部分的功能不像您认为的那样用于挂钩函数。像这样。

useEffect(() => {
  getData() // it handles the setting up the data variable part
}, []); // If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument.

useEffect(() => {
  refreshToken();
  getChart(); // it only sets the chart up, nothing else
}, [data]); // our component re-renders with every change on the var data

你可以有任意多的 useEffect 块,你可以从你的 ctx 中删除 getContext("2d") 部分。