簡體   English   中英

無法顯示從 API 獲取的數據

[英]Can't display fetched data from API

我是新手,我正在嘗試練習我在課程中學到的知識。 我正在做一個由 openweather api 提供的天氣應用程序。 我得到所有數據的回復,但是當我試圖顯示它們時它不起作用。 你能給我任何建議嗎?

這是我的代碼:

 import React, { useState, useEffect } from 'react'; import './App.css'; import Weather from './Weather'; const App = () => { const [weather, setWeather] = useState([]); useEffect(() => { getWeather(); }, []); let lat; let lon; const getWeather = () => { if(navigator.geolocation){ navigator.geolocation.getCurrentPosition(position => { lon = position.coords.longitude; lat = position.coords.latitude; const APP_KEY = "e802333933a66ec7a7588d658785ad09"; const API = `https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&cnt=5&APPID=${APP_KEY}`; fetch(API) .then(response => { return response.json(); }) .then(data => { setWeather(data.list); console.log(setWeather); }) }); } } return ( <div className="App"> <div> {weather.map(w => ( <Weather temperature={w.list.main} weather={w.list.weather.description}/> ))} </div> </div> ); } export default App;
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

沒有看到 API 返回的數據並且不知道你的狀態的形狀(你能在你的問題中發布 console.log 輸出嗎),看起來你需要這樣做:

<Weather temperature={w.main} weather={w.weather.description}/>

當您在此處設置狀態時,您已經在響應中解構了列表屬性:

.then(data => {
   setWeather(data.list);
   console.log(setWeather);
})

您還可以在渲染函數中放置一個console.log以查看您嘗試渲染的狀態的形狀。

據我所知,當您映射狀態時,在渲染方法中拋出錯誤,就在這里:

<Weather temperature={w.list.main}

該元素上沒有list屬性。

很確定在 React 中你可以調試這樣的事情,像這樣:

{
  weather.map(w => {
    console.log(w)
    return <Weather temperature={w.list.main} weather={w.list.weather.description}/>
  })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM