繁体   English   中英

如何在反应中显示来自api的数据

[英]How to display data from the api in react

我想学习如何在 reactjs 中显示来自 API 的数据。

这是API ,我想在weather[0]对象中的 API 和main对象中的temp属性中显示description属性。

怎么做 ?

这是代码:

    import logo from './Images/logo.png';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Navbar, Button, Form, FormControl } from 'react-bootstrap';
import React, { Component } from "react";


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

  }

  componentDidMount() {
    if (navigator.geolocation) {
      navigator.geolocation.watchPosition(async function (position) {
        console.log("Latitude is :", position.coords.latitude);
        console.log("Longitude is :", position.coords.longitude);

        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();
        
        console.log(data);
      });
    }
  }

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

        <Navbar bg="light" expand="lg">
          <Navbar.Brand href="#">Weather Forecast <img src={logo} alt="logo" width="50" height="50" /></Navbar.Brand>
          <Navbar.Toggle aria-controls="navbarScroll" />
          <Navbar.Collapse id="navbarScroll">

            <Form className="d-flex">
              <FormControl
                type="search"
                placeholder="Enter City"
                className="mr-2"
                aria-label="Search"
              />
              <Button variant="outline-success" className="searchBTN">Forecast</Button>
            </Form>
          </Navbar.Collapse>
        </Navbar>

      </div>
    );
  }
}

export default App;

我可以获得一些如何在页面上显示这些属性的示例吗?

解决了

只需用async (position) =>替换navigator.geoposition函数中的async function (position) ,数据就会成功。

您为 api 提供了另一个 url,但在您的代码中,您正在使用一些参数调用另一个 url。 但是,如果我们假设 url 是您在问题中提到的那个。 您可以调用 api 并将结果如下所示:

import "./styles.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { Navbar, Button, Form, FormControl } from "react-bootstrap";
import React, { Component } from "react";

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

  componentDidMount() {
    const url =
      "https://api.openweathermap.org/data/2.5/weather?q=plovdiv&units=metric&appid=ca148f5dc67f12aafaa56d1878bb6db2";
    fetch(url)
      .then((response) => response.json())
      .then((data) => this.setState(data))
      .catch((e) => {
        console.log(e);
      });
  }

  renderWeatherDescription = () => {
    if (this.state && this.state.weather && this.state.weather[0])
      return <p>{this.state.weather[0].description}</p>;
  };

  renderMainTemp = () => {
    if (this.state && this.state.main) return <p>{this.state.main.temp}</p>;
  };

  render() {
    return (
      <div className="App">
        <Navbar bg="light" expand="lg">
          <Navbar.Brand href="#">
            Weather Forecast <img alt="logo" width="50" height="50" />
          </Navbar.Brand>
          <Navbar.Toggle aria-controls="navbarScroll" />
          <Navbar.Collapse id="navbarScroll">
            <Form className="d-flex">
              <FormControl
                type="search"
                placeholder="Enter City"
                className="mr-2"
                aria-label="Search"
              />
              <Button variant="outline-success" className="searchBTN">
                Forecast
              </Button>
            </Form>
          </Navbar.Collapse>
        </Navbar>
        {this.renderWeatherDescription()}
        {this.renderMainTemp()}
      </div>
    );
  }
}

export default App;

这是可执行示例:

编辑美妙的霜iehtc

您也可以使用导航器查看此链接以获取完整答案:

编辑居高临下的冲浪luoue

就位,你有 console.log(data); 只需调用 this.setState({ ...something })。

您将对象传递给 setState,因此您传递的所有内容都保存到状态。

this.setState 也会触发自动重新渲染,所以如果你在 rendet 方法 this.state 中使用,变量会被更新和重新渲染。

<div>{this.state.xxx}</div>

您还可以渲染集合。

<div>{this.state.someArray.map((item) => item.description)}</div>

我不确切知道 API 响应的样子,您可以通过控制台记录它以查看响应的确切结构。 这是一个如何根据您对响应对象的描述来呈现它的示例。 您要做的第一件事是将响应对象放入状态,第二件事是将其显示在渲染方法中(从状态)。

import logo from './Images/logo.png';
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Navbar, Button, Form, FormControl } from 'react-bootstrap';
import React, { Component } from "react";


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

  }

  componentDidMount() {
    if (navigator.geolocation) {
      navigator.geolocation.watchPosition(async (position) => {
        console.log("Latitude is :", position.coords.latitude);
        console.log("Longitude is :", position.coords.longitude);

        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();
        
        console.log(data);

        this.setState(data);
      });
    }
  }

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

        <Navbar bg="light" expand="lg">
          <Navbar.Brand href="#">Weather Forecast <img src={logo} alt="logo" width="50" height="50" /></Navbar.Brand>
          <Navbar.Toggle aria-controls="navbarScroll" />
          <Navbar.Collapse id="navbarScroll">

            <Form className="d-flex">
              <FormControl
                type="search"
                placeholder="Enter City"
                className="mr-2"
                aria-label="Search"
              />
              <Button variant="outline-success" className="searchBTN">Forecast</Button>
            </Form>
          </Navbar.Collapse>
        </Navbar>

        <div>
            <p>{this.state.weather && this.state.weather[0].description}</p>
            <p>{this.state.main && this.state.main.temp}</p>
        </div>
      </div>
    );
  }
}

export default App;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM