第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

如何在 React 中自動發(fā)出 API 請求?

如何在 React 中自動發(fā)出 API 請求?

婷婷同學(xué)_ 2024-01-18 16:07:33
我正在嘗試為我的瀏覽器創(chuàng)建自定義主頁。我已經(jīng)實(shí)現(xiàn)了一個 API 來顯示天氣,但只有當(dāng)我按 Enter 時才有效。我想在加載頁面時自動顯示數(shù)據(jù),無需按 Enter 鍵,自動顯示布里斯托爾天氣,當(dāng)我輸入另一個位置時,API 將能夠請求和呈現(xiàn)。我嘗試了很多方法,例如(刪除鉤子,更改鉤子的初始狀態(tài),但似乎沒有任何效果)這是我的代碼:    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 的新手,這有點(diǎn)令人困惑,因?yàn)樵谶@里我使用相同的文件進(jìn)行編碼和渲染,我之前這樣做過,但我使用的是帶有 Express 的純 JavaScript 等......并且我渲染為 HTML。
查看完整描述

2 回答

?
嚕嚕噠

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個贊

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



查看完整回答
反對 回復(fù) 2024-01-18
?
達(dá)令說

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

更多資源:


查看完整回答
反對 回復(fù) 2024-01-18
  • 2 回答
  • 0 關(guān)注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號