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

ukqbszuj  于 2021-09-29  发布在  Java
关注(0)|答案(3)|浏览(280)

我想学习如何在reactjs中显示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;

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

p8h8hvxi

p8h8hvxi1#

您为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;

以下是可执行示例:https://codesandbox.io/s/wonderful-frost-iehtc
您还可以使用navigator查看此链接以获取完整答案:https://codesandbox.io/s/condescending-surf-luoue

hiz5n14c

hiz5n14c2#

在这里,您有console.log(数据);就叫这个.setstate({…某物})。
将对象传递给setstate,所以传递的所有内容都保存到state。
this.setstate还会自动触发重新渲染器,因此如果在render方法this.state中使用,则会更新变量并重新渲染。

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

也可以渲染集合。

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

ffvjumwh3#

我不知道api响应到底是什么样子的,您可以通过控制台记录它来查看响应的确切结构。这是一个如何根据您对响应对象的描述进行渲染的示例。您要做的第一件事是将响应对象置于状态,第二件事是在render方法中显示它(从状态)。

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);

        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[0].description}</p>
            <p>{this.state.main.temp}</p>
        </div>
      </div>
    );
  }
}

export default App;

相关问题