亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 React 中自動發出 API 請求?

如何在 React 中自動發出 API 請求?

婷婷同學_ 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貢獻1784條經驗 獲得超7個贊

useEffect( () => search(), [])



查看完整回答
反對 回復 2024-01-18
?
達令說

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)}

更多資源:


查看完整回答
反對 回復 2024-01-18
  • 2 回答
  • 0 關注
  • 170 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號