簡體   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