首页 > 解决方案 > 如何在反应中显示来自api的数据

问题描述

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

这是API,我想description在 API 中显示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;

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

解决了

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

标签: javascriptreactjs

解决方案


就位,你有 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>

推荐阅读