![](/img/trans.png)
[英]ReactJs: Uncaught TypeError: Cannot read properties of undefined (reading '0')
[英]Uncaught TypeError: Cannot read properties of undefined (reading 'name') - ReactJS
import Info from "./components/Info";
import Search from "./components/Search";
import axios from "axios";
import { useEffect, useState } from "react";
const App = () => {
const API_KEY = `<REDACTED>`
const baseURL = `http://api.weatherapi.com/v1/current.json?key=${API_KEY}&q=`
const [weatherData, setWeatherData] = useState({})
const [search, setSearch] = useState('London')
const [error, setError] = useState('')
useEffect(() => {
axios.get(`${baseURL + search}`)
.then(resp => {
setWeatherData(resp.data)
})
.catch(error => setError(error.message))
}, [search])
console.log(weatherData.location.name);
return (
<div className="App">
<h1 style={{ textAlign: 'center', marginBottom: '2rem' }}>{error}</h1>
<Search setSearch={setSearch} />
<div className="container">
<Info weatherData={weatherData} />
</div>
</div>
);
}
export default App;
我正在嘗試創建一個天氣應用程序來做出反應。 我正在使用您可以在代碼中看到的天氣 API(也許您也應該看看 API 結構)。 當我控制台登錄weatherData.location時,我得到了正常的天氣數據。 但是當我嘗試weatherData.location.name時,我收到錯誤消息: Uncaught TypeError: Cannot read properties of undefined (reading 'name') 。 我兩周前開始學習 React,所以我還是個初學者……謝謝。
當 API 尚未發送響應且天氣數據仍為空時,就會發生這種情況。 我建議添加一個[loading,setLoading]
狀態並將其默認設置為 true。 然后在.then(resp =>
函數中將其設置為 false。使用 if 語句檢查加載是否為 false,如果是,則打印/渲染 weatherData 的內容。
您需要在 console.log 中添加三元運算符
比如 console.log(weatherData? location ? .name ) 或者你可以試試 console.log(weatherData && weatherData.location && weatherDataname.location.name)
它的發生是因為在初始狀態下它無法讀取 name 的值,因為它可能是一個空字符串。
試試這個方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.