為什么這個天氣 Obj 中的某些屬性是可訪問的(第一層),但第二層無法訪問?Obj見下
uj5u.com熱心網友回復:
您的網址有問題,第一次渲染weather.main.temp也是未定義的,因為 api 請求是異步代碼。下面的代碼在這里作業:
const Weather=(props)=>{
const{capital, api_key} = props;
const [weather, setWeather] = useState('');
useEffect(() => {
axios
.get(`https://api.openweathermap.org/data/2.5/weather?q=${capital}&appid=${api_key}`)
.then(response => {
setWeather(response.data)
})
}, [])
console.log('weather', weather)
return(
<div>
<div> temperature {weather.visibility} Celcius</div>
<img src='http://openweathermap.org/img/wn/[email protected]' alt="flag" width="120" height="100"></img>
<p>wind {weather?.main?.temp} m/s</p>
</div>
)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/428963.html
上一篇:React,如何在React中使用reduce操作分組后的json
下一篇:將回應值的狀態推送到依賴項
