【问题标题】:How to put new object into array of objects in state如何将新对象放入状态对象数组中
【发布时间】: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


    【解决方案1】:

    以您目前的方式,您正在设置俄亥俄州的天气信息,然后将其替换为加利福尼亚州的天气信息。

    您的目标是首先将俄亥俄州的天气信息添加到数组中,然后将加利福尼亚州的天气信息作为第二个元素添加到该数组中。

    你会这样做:

    let ohioWeather = {description: "your stuff", icon: "...", temp: "...", city: "..."};
    // the line below clones the previous "data" array and appends the ohioWeather element to the new resulting array
    setData([...data, ohioWeather]);
    

    加利福尼亚天气对象也是如此。

    【讨论】:

      【解决方案2】:

      这样做:

      setData( pre => [...pre,{ description: res.data.weather[0].description,icon: res.data.weather[0].icon,temp: res.data.main.temp,city: res.data.name}]);
      

      【讨论】:

        【解决方案3】:

        您在每次获取后都会覆盖数据。 在开始使用 axios.get 之前尝试创建一个数组,将每个响应推送到该数组,最后执行: 设置数据(arr)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-07-01
          • 1970-01-01
          • 2021-09-09
          • 1970-01-01
          • 2021-07-18
          • 2021-01-24
          • 2022-01-06
          • 1970-01-01
          相关资源
          最近更新 更多