简体   繁体   English

无法显示从 API 获取的数据

[英]Can't display fetched data from API

I'm new to react and I'm trying to practice what i learnt in my course.我是新手,我正在尝试练习我在课程中学到的知识。 I'm doing a weatherapp provided with openweather api.我正在做一个由 openweather api 提供的天气应用程序。 I'm getting back response with all the data but when i'm trying to display them its not working.我得到所有数据的回复,但是当我试图显示它们时它不起作用。 Can you give me any suggestions please ?你能给我任何建议吗?

here is my code:这是我的代码:

 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>

Without seeing the data that the API returns and knowing the shape of your state (can you post the console.log output in your question please), it looks like you need to do this:没有看到 API 返回的数据并且不知道你的状态的形状(你能在你的问题中发布 console.log 输出吗),看起来你需要这样做:

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

You already destructured the list property in the response when you set the state here:当您在此处设置状态时,您已经在响应中解构了列表属性:

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

You can also put a console.log in your render function to see the shape of the state you are trying to render.您还可以在渲染函数中放置一个console.log以查看您尝试渲染的状态的形状。

The error is being thrown, from what I can tell, in the render method when you are mapping through the state, right here:据我所知,当您映射状态时,在渲染方法中抛出错误,就在这里:

<Weather temperature={w.list.main}

The element does not have a list property on it.该元素上没有list属性。

Pretty sure that in React you can debug things like this, like this:很确定在 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