为什么当我获取数据时它没有填充 useState?

Why is it not filling the useState whin i get the data?

我关注了这个页面:https://blog.logrocket.com/using-chart-js-react/ 数据加载到数据中,我在控制台中看到但数据未加载到 useState

import React, { useEffect, useState } from "react";
import budgetApi from "../api/budgetApi";
import { Bar } from "react-chartjs-2";
const BarChart = () => {
  const [chartData, setChartData] = useState({});

  useEffect(() => {
    getDataFromChart();
  }, []);

  const getDataFromChart = async () => {
    try {
      const response = await budgetApi.getByCategory();
      const data = response.data;
      setChartData({
        labels: [data.map((budget) => budget.category)],
        datasets: [
          {
            label: "Forint",
            data: [data.map((budget) => budget.total_amount)],
            backgroundColor: ["#ffbb11", "#ecf0f1", "#50AF95"],
            borderWidth: 1,
          },
        ],
      });
      console.log(chartData); //Empty!
    } catch (error) {
      console.log(error);
    }
  };
  return (
    <div>
      {
        <Bar
          data={chartData}
          options={{
            plugins: {
              title: {
                display: true,
                text: "Cryptocurrency prices",
              },
              legend: {
                display: true,
                position: "bottom",
              },
            },
          }}
        />
      }
    </div>
  );
};

export default BarChart;

我收到一些错误,例如:无法访问 属性“地图”,nextDatasets 未定义 我想我明白了,因为图表数据是空的。

请帮忙。 感谢您的回答

您没有获得 console.log 中的数据,因为 setChartData 确实改变了状态,但改变后的状态在下一行仍然不可用。

你得到这个错误是因为,在最开始,在异步调用之后数据加载到对象之前,对象是 {},所以它是空的并且没有任何键。

您应该避免在加载数据之前显示 Bar 组件,因此您可以设置加载状态或检查对象中您期望的任何键,例如

if (chartData.data) {
  return <Bar />; // With the props you need
}
return <></>;
const [chartData, setChartData] = useState({});

您已将初始状态设置为空对象。在您的第一次渲染中,您将那个空对象传递给 <Bar data={chartData}><Bar> 不期望空对象,因此它在 this line of code.

上抛出异常

你最终确实加载了数据,但错误发生在这之前。因此,当您等待数据加载时,您需要要么根本不呈现条形图,要么将其传递给足够多的虚拟数据数据以使其能够完成其工作。例如:

const [chartData, setChartData] = useState(null); // null is easier to check for than {}

// ...

return (
  <div>
    {!chartData ? (
      <span>Loading...</span>
    ) : (
      <Bar
        data={chartData}
        options={{
        // etc
      />

    )}
  </div>
);

console.log(chartData); //Empty!

此日志语句让您误入歧途。这将始终显示旧图表数据,即使您已成功设置状态。如果你想验证你的组件是否正在重新渲染,那么将你的日志语句放在组件的主体中(你仍然需要修复我在顶部提到的问题)

有关此日志语句为何不起作用的更多信息,请参阅此问题: