當用戶未在搜索欄中搜索任何內容時,我正在嘗試從 api 設定默認 url。最好的方法是什么?這是更好解釋的代碼:
const [img, setImg] = useState("");
const defaultUrl `https://api.unsplash.com/search/photos?page=1&query=chefs&client_id=${clientId}&per_page=20`;`
const url = `https://api.unsplash.com/search/photos?page=1&query=${img}&client_id=${clientId}&per_page=20`;
const { response, loading, error } = useFetch(url);
const handleSearchChange = (e) => {
setImg(e.target.value);
};
return (
<div className="container-fluid">
{loading && <p>Loading...</p>}
{error && <p>Something went wrong...</p>}
{response && response === null ? (
<>
<div className="row">
<div className="col-12 d-flex justify-content-center align-items-center input">
<input
className="col-3 form-control-sm py-1 fs-4 text-capitalize border border-3 border-dark"
type="text"
placeholder="Search Anything..."
value={img}
onChange={handleSearchChange}
/>
;
</div>
</div>
<div className="row">
<div className="col-12 d-flex justify-content-evenly flex-wrap">
{response.results.map((val) => {
return (
<img
key={val.id}
className="col-3 img-fluid img-thumbnail"
src={val.urls.small}
alt="val.alt_description"
/>
);
})}
</div>
;
</div>
</>
) : (
// Other div with default values gotten from default api url
)}
</div>
);
當沒有回應時,嘗試以某種方式更改 Usefetch 呼叫的 url。我正在考慮為影像制作一個單獨的組件,但不確定如何實作 usefetch 所以它是動態的。
uj5u.com熱心網友回復:
如果您的 useFetch 掛鉤對更改做出反應,那么...
useFetch( img === "" ? defaultUrl : `https://api.unsplash.com/search/photos?page=1&query=${img}&client_id=${clientId}&per_page=20 `
或者對于更簡潔的代碼,創建一個 getUrl 函式
// this outside component so it doesn't recreate on every render
const getUrl = (img) => {
return `https://api.unsplash.com/search/photos?page=1&query=${img}&client_id=${clientId}&per_page=20`
}
// then use it this way
useFetch(img === "" ? defaultUrl : getUrl(img))
您甚至可以通過將條件檢查放入 getUrl() 函式來更進一步
const getUrl = (img) => {
return img === "" ? default Url : `https://api.unsplash.com/search/photos?page=1&query=${img}&client_id=${clientId}&per_page=20`
}
//then...
useFetch(getUrl(img))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/522326.html
標籤:反应api反应钩子
下一篇:不知道物件位置的陣列斷言
