图表未显示更新的数据

Chart is not displaying updated data

我用过https://www.npmjs.com/package/react-chartjs-2,它第一时间显示了一个有数据的图表。但是每当我尝试使用新数据和数据集重新绘制时,它总是在图表上显示以前的图形数据。

我尝试过以下解决方案:https://github.com/reactchartjs/react-chartjs-2

也试过给参考

但是,它仍然显示与第一次加载相同的数据。

显示图表的代码,

 <Line
      data={graphData}
      redraw
      options={options}
      height="100px"
      weight="100px"
 />

在此, graphData 是, const [graphData, setGraphData] = useState(数据);

重绘, 我也试过,redraw={true}

When the data will be modified, I use setGraphData(updatedData) to update the chart, I have also checked whether data is changed or not.

图表中的数据数据更新但未显示在图表上

其中指定为graphData默认数据的数据,

const data = {
    labels: months,
    datasets: [
        {
            label: "# of Users",
            data: [0, 64, 129, 193, 258, 322, 387, 451, 516, 580],
            fill: false,
            backgroundColor: "rgb(255, 99, 132)",
            borderColor: "rgba(255, 99, 132, 0.2)",
            yAxisID: "y-axis-1",
        },
        {
            label: "# of Orders",
            data: [0, 25, 50, 76, 101, 126, 151, 177, 202, 227],
            fill: false,
            backgroundColor: "rgb(54, 162, 235)",
            borderColor: "rgba(54, 162, 235, 0.2)",
            yAxisID: "y-axis-2",
        },
    ],
};

我正在创建此数据的副本,然后在 setGraphData()

中分配

任何人都可以帮我解决这个问题!提前致谢!!

没有看到代码,这里只有一种解决方案。为图表组件提供密钥并在数据更新后更新密钥,

<chart key={getKey()} data={data} />

获取密钥将创建一个关于新数据的唯一密钥。

  const getKey = () => {
    return data?.map((p) => p.id)?.join();
  };

这里唯一重要的是如果数据更新,getKey 方法应该 return 一个新值 JSON.stringify(data) 是最简单的选择(我不确定这是否是一个好的方法提供序列化数据作为密钥,但它肯定会起作用)

重新渲染背后的问题是定义为调用后端 API 处理程序并将数据分配给折线图的函数。

之前 - 不工作

useEffect(() => {
      ...
      the function which has code to call and fetch data from back-end API/handler
    }, []);

之后 - 工作

useEffect(() => {
       ...
       Code which calls back-end API/handler function to fetch data for graph
       ...
    }, []);

我也保留了重绘,

<Line
     key={JSON.stringify(graphData)}
     data={graphData}
     redraw
     options={options}
     height="100px"
     weight="100px"
 />