将 Axios 添加到 React 图表并获取 JSON 数据

Add Axios to React chart and take JSON data

我目前正在练习 React 并习惯使用图表。

我在使用 React 图表和调用 Axios 从在线 JSON 文件中获取信息时遇到了困难。

它与预编程值完美配合,但使用 Axios 调用时它不会产生结果。

我对如何以正确的方式将 Axios 应用于现有代码有疑问!非常感谢任何帮助。

 import React, { Component } from "react";
 import { Doughnut } from "react-chartjs-2";
 import axios from "axios";

 const headingStyle = {
  "text-align": "center"
  };

  const data = {
  labels: ["In", "out", "Balance"],
 datasets: [
 {
 //   data: [300, 100, 200],
  backgroundColor: ["#27DD73", "#FF2400", "#36A2EB"],
  hoverBackgroundColor: ["#27DD73", "#FF2400", "#36A2EB"]
  }
    ]
  };



 class DoughnutExample extends Component {
 async componentDidMount() {
    const { data: users } = await axios.get(
      "https://api.myjson.com/bins/bw0u4"
    );
    this.setState({ users });
  }
 render() {
 return (
  <div className="card card-1" style={{ padding: "10px" }}>
    <h3 style={headingStyle}>Cash Flow</h3>
    <Doughnut data={data} />
  </div>
 );
   }
 }

export default DoughnutExample;

我的 JSON 文件在这里:https://api.myjson.com/bins/bw0u4

我想从 JSON 中获取 "chart" 数据。

render 中没有 data 变量。由于响应存储到状态,因此应该相应地使用它:

<Doughnut data={this.state.users} />

如果打算从数组元素中获取 chart 键,则应重新映射数组:

this.setState({ users: users.map(({ chart }) => chart) });

除此之外还有no problems with this snippet.