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

How to display chart (rechart) with data from API in ReactJS

从这个 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_txtlist[39].main.temp, list[39].dt_txt 的所有对象放入其中,并在 x 中显示这些数据和图表上的 y 轴。有没有办法得到一些例子,如何把我的 dataForecast 从 API 放在图表中?

更新

我用静态数据创建了一个 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
    }));

从后端获取数据后调用一次该方法,将结果设置到state中,提供给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。请查看它是否能满足您的需求。