javascript - 如何在反应中显示来自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) =>
,数据就会成功。
解决方案
就位,你有 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>
推荐阅读
- postgresql - Postgres 函数 - 组合来自多个查询的对象数组
- regexp-replace - 正则表达式在多行文本中匹配字符后选择文本
- php - 如何使用相同的方法为相同的路由使用不同的可选中间件
- angular - 在动态添加行的表中,如何为Angular中的每一行创建不同的点击功能?
- hibernate - JPA中方法完成时如何更新数据库
- amazon-web-services - aws emr hive insert 语句给出错误为“辅助服务:mapreduce_shuffle 不存在”
- kotlin - 如何在 kotlin 中编写包含 mutex.withLock 的 getter 和 setter
- node.js - Node + vue js 用户离线/在线状态(服务器端)
- javascript - 单击按钮时,Ajax 不会中止
- excel - 获取运行时 1004:使用单元格时对象“_Worksheet”的方法“范围”失败