首页 > 解决方案 > 使用 reactjs 获取 API 并显示到图表中

问题描述

我正在尝试从https://api.data.gov.sg/v1/environment/air-temperature获取城市名称及其各自的温度,然后将其显示给 Graphs。那么,如何获取所有城市名称并将其设置为图形代码中的标签?下面是我的代码。我是 reactjs 的新手。因此,任何形式的帮助都将得到高度利用。

import React, { Component } from "react";
import axios from "axios";
import { Line } from "react-chartjs-2";
class Chart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      chartData: {},
      areas: [],
      temperature: [],
      all: {}
    };
  }
  componentDidMount() {
    axios
      .get("https://api.data.gov.sg/v1/environment/air-temperature")
      .then(res =>
        this.setState({
          all: res.data,
          areas: res.data.metadata.stations,
          temperature: res.data.items[0].readings
        })
      )
      .catch(err => console.log(err));
    this.getChartData();
  }
  getChartData() {
    console.log("length", this.state.areas);
    // Ajax calls here
    this.setState({
      chartData: {
        labels: [
          "Boston",
          "Worcester",
          "Springfield",
          "Lowell",
          "Cambridge",
          "New Bedford"
        ],
        datasets: [
          {
            label: "Population",
            data: [617594, 181045, 153060, 106519, 105162, 95072],
            backgroundColor: [
              "rgba(255, 99, 132, 0.6)",
              "rgba(54, 162, 235, 0.6)",
              "rgba(255, 206, 86, 0.6)",
              "rgba(75, 192, 192, 0.6)",
              "rgba(153, 102, 255, 0.6)",
              "rgba(255, 159, 64, 0.6)",
              "rgba(255, 99, 132, 0.6)"
            ]
          }
        ]
      }
    });
  }
  render() {
    //console.log(this.state.areas);
    return (
      <div style={{ position: "relative", width: 500, height: 500 }}>
        <h1>Chart</h1>
        <Line data={this.state.chartData} />
      </div>
    );
  }
}

export default Chart;

标签: javascriptreactjs

解决方案


您可以使用数组的map方法areas来遍历其中的元素areas并获取每个元素的名称。

例如(取自给定 API 端点的数据,具体来说data.metadata.stations):

const areas = [
    { id: 'S117',
    device_id: 'S117',
    name: 'Banyan Road',
    location: { latitude: 1.256, longitude: 103.679 } },
    { id: 'S50',
    device_id: 'S50',
    name: 'Clementi Road',
    location: { latitude: 1.3337, longitude: 103.7768 } },
    { id: 'S107',
    device_id: 'S107',
    name: 'East Coast Parkway',
    location: { latitude: 1.3135, longitude: 103.9625 } },
]

const areaNames = areas.map(e => e.name);

结果为areaNames

[ 'Banyan Road', 'Clementi Road', 'East Coast Parkway' ]

推荐阅读