大家好,我在 React 中構建了一個天氣應用程式,我想將狀態變數“city”設定為輸入值,以便我可以將其重新插入 API URL,但我必須單擊兩次才能正確顯示 API。第一次單擊回傳“錯誤:請求失敗,狀態碼 400”。
這是我從中獲取 API 的地方:
const URL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${APIKey}`;
這是我的 API 呼叫:
const getCity = () => {
axios
.get(URL)
.then(function (response) {
setWeatherData(response.data);
})
.catch(function (err) {
console.warn(err);
});
};
這是我遇到問題的功能...
function handleChange() {
const bar = document.getElementById("input-field").value;
if (bar.indexOf(" ") > -1) {
setCity(bar.split(" ").join(" "));
} else {
setCity(bar);
}
}
這是 JSX:
<input
id="input-field"
className="searchbar"
type="text"
placeholder="Name of city (e.g. Austin"
/>
<button
className="searchbtn"
onClick={() => {
handleChange();
getCity();
}}
>
search
</button>
uj5u.com熱心網友回復:
問題在于city,因此URL僅在下一次渲染時評估,而不是立即評估。
getCity()從您的處理程式中洗掉onClick并將其添加useEffect()到取決于city
useEffect(() => {
axios.get("https://api.openweathermap.org/data/2.5/weather", {
params: {
q: city,
appid: APIKey
}
})
.then(({ data }) => setWeatherData(data))
.catch(console.warn)
}, [ city ])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/426496.html
