【发布时间】:2020-04-23 20:27:18
【问题描述】:
我正在尝试通过钩子实现 api 调用,但我不知道为什么状态没有更新。有人可以看看这个并告诉我原因:
import React,{useState} from 'react';
function Weather(){
var [weat,setWeat]=useState({city:'',report:[]})
var UpdateCity = event =>{
setWeat({...weat,city:event.target.value});
}
var UpdateReport = event =>{
var addr="http://api.openweathermap.org/data/2.5/weather?q="+weat.city+"&appid=04e"
console.log(addr);
fetch(addr)
.then(res=>res.json())
.then(res=>{
setWeat({...weat,report:res});
});
}
return(
<>
<h1>Welcome to my weather App</h1>
<h3>Please enter your city</h3>
<input type='text' onChange={UpdateCity} placeholder='Enter your City'></input>
<input type='submit' onClick={UpdateReport}></input>
</>
)
}
export default Weather;
【问题讨论】:
-
你在传递api密钥吗?
-
是的,我通过了。我只是在这里掩盖了它
-
尝试添加 catch 块并记录 error.message 然后您将能够看到错误是什么,然后在问题中更新该错误,以便找到它会有所帮助
-
也许将您的状态拆分出来,使用两个状态挂钩并独立使用/更新它们会更容易。或者使用状态更新功能,
setWeat(prevWeat => { /* copy, mutate, return */ })
标签: reactjs api react-hooks