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

时间:2020-05-27 21:29:14

标签: reactjs react-hooks 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;

1 个答案:

答案 0 :(得分:0)

您是否尝试过以下方法:

          <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>
  );