使用Reactjs获取API并显示为图形

时间:2019-10-14 03:10:37

标签: javascript reactjs

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

3 个答案:

答案 0 :(得分:0)

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

例如(数据来自given API endpoint,特别是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' ]

答案 1 :(得分:0)

即使没有数据来自后端,您的getChartData()函数也会被调用 所以要保持标志 所以如果它是真的 从函数返回,不显示图表 在抓取为假而抓取为真时显示

答案 2 :(得分:0)

class Chart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      chartData: {}
    };
  }

  componentDidMount() {
    axios
      .get("https://api.data.gov.sg/v1/environment/air-temperature")
      .then(res =>{
        this.getChartData(res.data);
      })
      .catch(err => console.log(err));

  }
  getChartData( data) {
    const cityNames = data.metadata.stations.reduce((acc,cur) => [...acc,cur.name],[]);
    const temperatures = data.items[0].readings.reduce((acc,cur) => [...acc,cur.value],[])
    this.setState({
      ...this.state,
      chartData: {
        labels: cityNames,
        datasets: [
          {
            label: "Population",
            data: temperatures,
            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;

https://codesandbox.io/s/smoosh-silence-ykcqj