开发者问题收集

如何在 React 中显示来自 API 的数据

2021-07-27
1436

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

这是 API ,我想显示 API 中的 description 属性,该属性位于 weather[0] 对象中,以及 temp 属性,该属性位于 main 对象中。

怎么做?

这是代码:

    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;

我能否得到一些如何在页面上显示这些属性的示例?

已解决

只需将 navigator.geoposition 函数中的 async function (position) 替换为 async (position) => ,数据即可成功获取。

3个回答

您为 api 提供了另一个 url,但在您的代码中,您正在使用一些参数调用另一个 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;

这是可执行示例:

Edit wonderful-frost-iehtc

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

编辑 condescending-surf-luoue

Majid M.
2021-07-27

在有 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>
Arťom Pozdnyakov
2021-07-27

我不知道 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;
afalak
2021-07-27