javascript - 使用 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;
解决方案
您可以使用数组的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' ]
推荐阅读
- powerapps - 当我们关闭并重新打开应用程序时,离线收集数据会发生什么
- hlsl - HLSL中的步骤与比较运算符?
- eclipse - 如何在 Eclipse/STS 或 Intellij Idea 中使用 lombok?
- vb.net - 如何从另一个类更改一个类的颜色属性?
- r - R Shiny中的右侧栏处理
- android - 当我们阻止屏幕截图时如何祝酒消息显示
- php - phpexcel输出在IE中立即消失
- shell - 每当在 Unix 邮箱服务器中收到新邮件时,如何运行 shell 脚本文件?
- c++ - C++ 使用 shared_ptr 连续分配内存
- javascript - Typescript async/await 转换为产生错误