我在 API 调用中收到“未定义” - React
2022-08-18
208
我正在开发一个天气应用项目。到目前为止,我在 API 调用方面遇到了很多问题。我认为原因是我的代码在 API 调用未完成之前就执行了。所以,我总是收到如下错误:
Uncaught TypeError: Cannot destructure property 'list' of 'takeData' as it is undefined
其他错误已解决。在我尝试将天气图标添加到我的项目之前,没有出现这样的错误。我有两个问题:
- 如何修复上述错误
- 为什么每当我尝试将新内容添加到项目时,都会抛出错误“未定义”
这是我的代码:
import axios from "axios"
import { useEffect, useState } from "react"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCloudSun } from '@fortawesome/free-solid-svg-icons'
import { faCloud } from '@fortawesome/free-solid-svg-icons'
function ApiCall({ getSelection }) {
const [takeData, setTakeData] = useState()
const [loading, setLoading] = useState(false)
const cloudSun = <FontAwesomeIcon icon={faCloudSun} />
const cloud = <FontAwesomeIcon icon={faCloud} />
useEffect(() => {
const fetchApi = async () => {
setLoading(true)
try {
const res = await axios(`https://api.openweathermap.org/data/2.5/forecast?q=${getSelection}&units=metric&appid=c681e6e33ec339728fdf88e0b24a2a01`)
setTakeData(res.data)
console.log(res.data)
} catch (err) {
console.log(err)
}
setLoading(false)
}
fetchApi()
}, [getSelection])
if (loading === true) {
return <div>Loading...</div>
}
const { list } = takeData
// console.log("IS UPDATED: ",city?.name)
return (
<div className="weather_card">
<div className="weather">{list?.map((el, idx) => (
<p key={idx} style={{ display: "inline-block", marginRight: "10px", paddingTop: "165px", boxSizing: "border-box", height: "200px", width: "150px", border: "1px solid grey" }} >{Math.round(el.main.temp)} °C / {el.weather[0].main} </p>
))}
</div>
</div>
)
}
export default ApiCall
1个回答
为 takeData 设置初始值,以便应用程序不会出错
const [takeData, setTakeData] = useState({list:[]})
Naren Murali
2022-08-18