【发布时间】:2021-09-10 01:03:44
【问题描述】:
基本上,我试图显示几个城市的天气,我必须发出一些 api 请求,然后获取数据并将其放入状态对象数组中,以便我可以映射并渲染它。问题是我不知道如何将一个新对象推入状态并创建一个对象数组。可能做错了,还在学习中。
import React, { useEffect, useState } from "react";
import axios from "axios";
import { Container, Card, ListGroup } from "react-bootstrap";
const WeatherPanel = () => {
const [data, setData] = useState([]);
const fetchData = () => {
axios
.get(`https://api.openweathermap.org/data/2.5/weather?q=${"Ohio"}&appid=${key}`)
.then((res) => {
setData({
description: res.data.weather[0].description,
icon: res.data.weather[0].icon,
temp: res.data.main.temp,
city: res.data.name,
});
console.log(data);
return axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${"California"}&appid=${key}`);
})
.then((res) => {
setData({
description: res.data.weather[0].description,
icon: res.data.weather[0].icon,
temp: res.data.main.temp,
city: res.data.name,
});
})
.catch((err) => {
console.log(err);
});
};
useEffect(() => {
fetchData();
}, []);
return (
<div>
<Container fluid>
<Card style={{ width: "50%", boxShadow: "0 0 10px 2px lightgrey" }}>
<Card.Header> Favorite Location</Card.Header>
<ListGroup variant="flush">
<ListGroup.Item>
<img src={`http://openweathermap.org/img/wn/${data.icon}@2x.png`} />
{data.city}
</ListGroup.Item>
</ListGroup>
</Card>
</Container>
</div>
);
};
export default WeatherPanel;
这就是我想要的状态
【问题讨论】:
标签: reactjs api axios react-hooks setstate