婷婷同學_
2024-01-18 16:07:33
我正在嘗試為我的瀏覽器創建自定義主頁。我已經實現了一個 API 來顯示天氣,但只有當我按 Enter 時才有效。我想在加載頁面時自動顯示數據,無需按 Enter 鍵,自動顯示布里斯托爾天氣,當我輸入另一個位置時,API 將能夠請求和呈現。我嘗試了很多方法,例如(刪除鉤子,更改鉤子的初始狀態,但似乎沒有任何效果)這是我的代碼: const [query, setQuery] = useState('Bristol'); const [weather, setWeather] = useState({});const search = async () => { fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`) .then(res => res.json()) .then(result => { setWeather(result); setQuery('') console.log(result) });} return( <div className="app"> <main> <div className="search-box"> <input type="text" className="search-bar" placeholder="Search..." onChange={e => setQuery(e.target.value)} value={query} onKeyPress={search} /> </div> {(typeof weather.main != "undefined") ? ( <div> <div className="location-box"> <div className="location">{weather.name}</div> <div className="date">{dateBuilder(new Date())}</div> </div> <div className="weather-box"> <div className="temp"> {Math.round(weather.main.temp)} </div> <div className="weather"> {weather.weather[0].main} </div> </div> </div> ) : ('')} </main> </div> )} 我是 ReactJS 的新手,這有點令人困惑,因為在這里我使用相同的文件進行編碼和渲染,我之前這樣做過,但我使用的是帶有 Express 的純 JavaScript 等......并且我渲染為 HTML。
2 回答

達令說
TA貢獻1821條經驗 獲得超6個贊
嘗試將調用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]);
第二個參數是所謂的依賴數組。每當其內容發生更改時,效果都會重新運行,請參閱https://reactjs.org/docs/hooks-effect.html。
也刪除,onKeyPress={search}
因為它是多余的onChange={e => setQuery(e.target.value)}
更多資源:
Robin Wieruch:如何使用 React Hooks 獲取數據?https://www.robinwieruch.de/react-hooks-fetch-data
添加回答
舉報
0/150
提交
取消