目前,我只能在國家名稱已經加載時提取資訊,我添加代碼,保存它,然后它在本地主機上更新。但是當我在另一個國家/地區輸入時,出現Uncaught TypeError: Cannot read properties of undefined (reading 'temp'). 例如,我的代碼{weather.main.temp}有效,但前提是之前已經設定了 state = "france"。
我的子組件:
const WeatherInfo = ({ country }) => {
const [weather, setWeather] = useState({});
useEffect(() => {
axios
.get(`https://api.openweathermap.org/data/2.5/weather?q=${country.capital}&appid=${api_key}&units=imperial`)
.then(response => {
console.log(response.data)
setWeather(response.data)
})
}, [country])
return (
<div>
<h3>Weather in {country.capital}</h3>
<p><b>Temperature</b>{weather.main.temp}</p>
</div>
)
}


uj5u.com熱心網友回復:
weather在WeatherInfo創建時被初始化為一個空物件。因此weather.main是未定義的,當您嘗試temp從未定義中獲取屬性時會出現錯誤。
您可以通過使用一些條件鏈接或一些三元運算子來解決此問題,具體取決于您想要在weather空物件時顯示的內容。
return (
<div>
<h3>Weather in {country.capital}</h3>
<p><b>Temperature</b>{weather.main?.temp}</p>
</div>
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/397928.html
標籤:javascript 反应 公理
