如何从 api 中解构数组对象并放入状态?

how to destructure object of arrays from api and put into state?

所以基本上我正在学习如何 api 调用并且我正在处理开放天气 api,试图显示几个不同城市的名称和温度。问题是响应是一个数组对象,并试图将所有城市的名称放入状态,以便我可以显示它们。将所有名称放入状态的最佳方法是什么?

import "./App.css";
import React, { useEffect, useState } from "react";
import axios from "axios";

function App() {
    const [cityName, setCityName] = useState("");
    const [temp, setTemp] = useState("");
    const [description, setDescription] = useState("");

    const fetchData = () => {
        //api variables (normily stored somewhere safer)
        const lat = "35.320696399999996";
        const lon = "-75.8232391";
        const key = "115475ac7a8dda2a7e7ec0b27b93ce35";
        const cnt = "5";
        const url = `https://api.openweathermap.org/data/2.5/find?lat=${lat}&lon=${lon}&cnt=${cnt}&appid=${key}`;

        axios
            .get(url)
            .then((res) => {
                
                console.log(res.data.list);
            })
            .catch((err) => {
                console.log(err);
            });
    };

    useEffect(() => {
        fetchData();
    }, []);

    return <div className="App"></div>;
}
export default App;

您可以使用 您想要的属性将响应列表映射到新数组。更新您的组件以使用单个“数据”状态数组来保存映射的响应值。

const [data, setData] = useState([]);

const fetchData = () => {
  
  ...

  axios
    .get(url)
    .then((res) => {
      console.log(res.data.list);

      // destructure name, main.temp, and weather
      const data = res.data.list.map(({ name, main: { temp }, weather }) => {
        // weather is an array of length 1, but still provide fallback
        const { description } = weather[0] ?? {};

        return {
          description,
          name,
          temp,
        };
      });

      setData(data);
    })
    .catch((err) => {
      console.log(err);
    });
};

useEffect(() => {
    fetchData();
}, []);