如何在 ReactJS 中使用来自 API 的数据显示图表rechart

问题描述

从这个 API 我想从 list[0].main.temp,list[0].dt_txtlist[39].main.temp,list[39].dt_txt

我想获取温度和日期,并希望在 Y 轴日期的 X 轴上显示温度。

import logo from './Images/logo.png';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Nav,Navbar,Button,Form,FormControl } from 'react-bootstrap';
import React,{ Component } from "react";
import { LineChart,Line,Cartesiangrid,XAxis,YAxis,Tooltip } from 'recharts';

const data = [
  { name: 'Page A',uv: 400,pv: 2400,amt: 2400 },{ name: 'Page B',uv: 600,pv: 2600,amt: 1800 },{ name: 'Page C',uv: 800,pv: 2800,amt: 1200 }
];
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    if (navigator.geolocation) {
      navigator.geolocation.watchPosition(async (position) => {

        var lat = position.coords.latitude;
        var lon = position.coords.longitude;

        const url = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
        const response = await fetch(url);
        let data = await response.json();

        this.setState(data);

        const urlForecast = `http://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
        const responseForecast = await fetch(urlForecast);
        let dataForecast = await responseForecast.json();

        this.setState(dataForecast);
      });
    }

  }

render() {
    return (
      <div className="App">


        <LineChart width={600} height={300} data={data} >
          <Line type="monotone" dataKey="uv" stroke="#8884d8" />
          <Cartesiangrid stroke="#ccc" strokeDasharray="5 5" />
          <XAxis dataKey="name" />
          <YAxis />
          <Tooltip />
        </LineChart>


      </div>
    );
  }
}

export default App;

现在我在导入的库下有数组 data 并希望将所有对象从 API list[0].main.temp,list[0].dt_txt 放入 list[39].main.temp,list[39].dt_txt 并在图表的 x 和 y 轴上显示此数据.有没有办法获得一些示例,如何将来自 API 的 dataForecast 放在图表中?

更新

我用静态数据创建了一个 data.js 文件并像这样使用:

    import weatherData from "./data";

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

  formatData = (data) =>
    data.map(({ dt_txt,main }) => ({
      // date -> Can be used as dataKey for XAxis
      //Further you can format the date as per your need
      date: dt_txt,// temp -> Can be used as dataKey for Line
      temp: main.temp
    }));

我的 componentDidMount() 看起来像这样:

 componentDidMount() {
if (navigator.geolocation) {
  navigator.geolocation.watchPosition(async (position) => {

    var lat = position.coords.latitude;
    var lon = position.coords.longitude;

    const url = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
    const response = await fetch(url);
    let data = await response.json();

    this.setState(data);

    const urlForecast = `http://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2`;
    const responseForecast = await fetch(urlForecast);
    let dataForecast = await responseForecast.json();

    this.setState(dataForecast);

    const fetchData = async () => {
      // Commenting as getting error while fetching
      // But here you can have logic of fetching the data and
      //add listeners etc
       let res = await fetch(
        `http://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2`
       );
       res = await res.json();

      //Here i'm using dummy promise to simulate the API call
      const promise = new Promise((res) => {
        setTimeout(() => {
          res(weatherData);
        },500);
      });
       res = await promise;

      //After getting the data from the backend,//format it as per how the LineChart is expecting
      this.setState({
        chartData: this.formatData(res.list)
      });
    };
    fetchData();
  });
}

}

如何在图表上使用来自fetchData函数的数据?

解决方法

据我所知,您只需要按照 LineLineChart 组件所期望的方式格式化数据。

  formatData = (data) =>
    data.map(({ dt_txt,main }) => ({
      // date -> Can be used as dataKey for XAxis
      //Further you can format the date as per your need
      date: dt_txt,// temp -> Can be used as dataKey for Line
      temp: main.temp
    }));

您可以在从后端获取数据后调用此方法一次并将结果设置在状态中并提供给LineChart 组件。

收到响应后,您可以调用 formatData 并获取格式化数据并将其设置为

this.setState({
  chartData: this.formatData(res.list)
});

最后,您可以将数据传递给 LineChartLine

<LineChart width={600} height={300} data={chartData}>
  <Line type="monotone" dataKey="temp" stroke="#8884d8" />
  <CartesianGrid stroke="#ccc" strokeDasharray="5 5" />
  <XAxis dataKey="date" />
  <YAxis />
  <Tooltip />
</LineChart>

我为此创建了 this sandbox。如果它满足您的需求,请检查一下。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...