2 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個贊
嘗試將調(diào)用fetch包裝在useEffect:
useEffect(() => {
fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
.then((res) => res.json())
.then((result) => {
setWeather(result);
console.log(result);
});
}, [query]);
第二個參數(shù)是所謂的依賴數(shù)組。每當(dāng)其內(nèi)容發(fā)生更改時,效果都會重新運(yùn)行,請參閱https://reactjs.org/docs/hooks-effect.html。
也刪除,onKeyPress={search}
因?yàn)樗嵌嘤嗟?code>onChange={e => setQuery(e.target.value)}
更多資源:
Robin Wieruch:如何使用 React Hooks 獲取數(shù)據(jù)?https://www.robinwieruch.de/react-hooks-fetch-data
添加回答
舉報