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

如何解决如何在 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。如果它满足您的需求,请检查一下。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?