【问题标题】:API Fetch with reactjs and show into graph使用 reactjs 获取 API 并显示到图表中
【发布时间】:2019-10-14 11:58:51
【问题描述】:

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

【问题讨论】:

  • areas 获取“名称”是什么意思?您还可以附上areas 的样例吗?
  • 基本上我想从此 API 获取所有“名称”,然后在 chartDate 函数下将其设置为“标签”。主要目的是显示带有城市名称及其温度的图表。

标签: javascript reactjs


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    您可以使用areas 数组的map 方法遍历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' ]
    

    【讨论】:

    • 我正在尝试上面的代码。但它在数组中显示零记录。
    • 你把areaNames 行放在哪里了?在哪个渲染上它是空的?因为它至少在第一次渲染时是空的。
    • @AMobin 是的,areas 尚未设置,因为它是异步设置的。由于 areaNames 是计算出来的并且您存储原始数据,因此您不应该也存储它。相反,将areaNames 的定义移至render 方法或render 调用的方法。或者将 componentDidMount 更改为 async 方法和 await axios.get 调用。
    【解决方案3】:

    当数据还没有来自后端时,您的 getChartData() 函数将被调用 所以保持一个标志获取 所以如果它是真的 从函数返回并且不显示图表 在 fetching 为 false 且 fetched 为 true 时显示它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 2013-06-02
      • 1970-01-01
      相关资源
      最近更新 更多