fetch正在用模板字符串返回一个空数组
我对城市的Usestate价值,默认的伦敦,无法与我的GetWeather功能中调用的获取值URL合作。当我不小心重新渲染代码时,它有时会运行,但没有其他时间
import './App.css';
import Daily from './components/daily';
import {useState, useEffect} from 'react'
function App() {
const [city, setCity] = useState('London')
const [weatherData, setWeather] = useState([])
const getWeather = async() =>{
try{
const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=f8d957da06af592a1390c360ea801908&units=metric`)
const pResp = await resp.json()
setWeather(pResp)
}
catch{
console.log('error')
}
}
useEffect(()=>{
getWeather()
},[])
return(
<>
<Daily {...weatherData}></Daily>
</>
)
}
export default App;
code here
My useState value of city, default London, isn't working with the fetch value URL being called in my getWeather function. It runs sometimes when I accidentally re-render the code but not any time else
import './App.css';
import Daily from './components/daily';
import {useState, useEffect} from 'react'
function App() {
const [city, setCity] = useState('London')
const [weatherData, setWeather] = useState([])
const getWeather = async() =>{
try{
const resp = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=f8d957da06af592a1390c360ea801908&units=metric`)
const pResp = await resp.json()
setWeather(pResp)
}
catch{
console.log('error')
}
}
useEffect(()=>{
getWeather()
},[])
return(
<>
<Daily {...weatherData}></Daily>
</>
)
}
export default App;
code here
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于,韦特达塔(Weatherdata
新代码
The problem was that the weatherData was being passed through before it fetched and formatted properly, to fix that I just added a loading screen and render delay so the data is always there
New Code