使用 react 钩子时如何在 react-chartjs 中使用动态数据?



我正在尝试使用 react-chartjs-2 制作条形图。我的状态中有图表数据,但由于数据来自 API,因此需要一些时间才能显示。我试图用if else解决它,但它没有用。我想知道在图表中放置动态数据的正确方法。

法典:

import React, { useContext, useEffect } from "react";
import { Bar } from "react-chartjs-2";
import { Context } from "../../../store/store";
import "./Chart.scss";
const Chart = () => {
const [state, dispatch] = useContext(Context);
console.log(state.audioFeatures);//data I want to show
const data = {
labels: [
"acousticness",
"danceability",
"energy",
"instrumentalness",
"liveness",
"speechiness",
"valence",
],
datasets: [
{
label: "My First dataset",
fillColor: "white",
backgroundColor: [
"rgba(255, 99, 132, 0.3)",
],
borderColor: [
"rgba(255,99,132,1)"
],
gridLines: { color: "white" },
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data:""
},
],
};
return (
<div className="chart-container">
<div>
{state.audioFeatures ? (
<Bar
data={data}
width={700}
height={500}
options={{
maintainAspectRatio: false,
}}
/>
) : null}
</div>
</div>
);
};
export default Chart;

你有没有尝试过这样的事情:

<Bar
data={state.audioFeatures}
...
/>

或:

const data = {
labels: [
...
],
datasets: [
{
...
data: state.audioFeatures 
},
],
};
return (
<div className="chart-container">
<div>
{state.audioFeatures ? (
<Bar
data={data}
...
/>
) : null}
</div>
</div>
);

相关内容

  • 没有找到相关文章

最新更新