当用户不在搜索栏中搜索任何内容时,我尝试从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,因此它是动态的。
发布于 2022-10-26 12:16:30
如果您的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://stackoverflow.com/questions/74207561
复制相似问题