如何在Chart.js和React.js中使用Axios API

问题描述 投票:0回答:1

我使用Axios和useEffect提取了数据,并希望通过Chart.js显示它但只有图表框不显示数据。

下面是我的代码

 import React, { useState, useEffect } from "react";
 import { Bar, Line } from "react-chartjs-2";
import axios from "axios";

function ChartSix() {

  const [data, setData] = useState([]);
  const [posts, setPosts] = useState([]);

  let title = [];
  let id = [];
  useEffect(() => {

    axios.get("https://jsonplaceholder.typicode.com/posts").then(res => {
      const ipl = res.data;
      setPosts(ipl);

      ipl.forEach(record => {
        title.push(record.title);
        id.push(record.id);
      });

      setData({
        Data: {
          labels: title,
          datasets: [
            {
              label: "IPL 2018/2019 Top Run Scorer",
              data: id,
              backgroundColor: [
                "#3cb371",
                "#0000FF",
                "#9966FF",
                "#4C4CFF",
                "#00FFFF",
                "#f990a7",
                "#aad2ed",
                "#FF00FF",
                "Blue",
                "Red"
              ]
            }
          ]
        }
      });
    });
  });

  return (
    <div>
      <Line data={data}></Line>
    </div>
  );
}

export default ChartSix;

enter image description here

javascript reactjs axios chart.js
1个回答
1
投票

适用于:

  return (
    <div>
      <Line data={data.Data} />
    </div>
  )

https://codesandbox.io/s/frosty-torvalds-qzwt3

© www.soinside.com 2019 - 2024. All rights reserved.