【问题标题】:How to use dynamic data in react-chartjs when using react hooks?使用 react 钩子时如何在 react-chartjs 中使用动态数据?
【发布时间】:2020-05-27 21:29:14
【问题描述】:

我正在尝试使用 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;

【问题讨论】:

    标签: reactjs react-hooks react-chartjs


    【解决方案1】:

    您是否尝试过类似的方法:

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

    【讨论】:

      猜你喜欢
      • 2021-09-29
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 2021-11-20
      • 2020-11-17
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      相关资源
      最近更新 更多