首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用不同的API调用有条件地呈现一个React应用程序的最佳方法是什么?

使用不同的API调用有条件地呈现一个React应用程序的最佳方法是什么?
EN

Stack Overflow用户
提问于 2022-10-26 12:12:26
回答 1查看 19关注 0票数 0

当用户不在搜索栏中搜索任何内容时,我尝试从api中设置默认的url。什么是最好的方法?下面是一个更好解释的代码:

代码语言:javascript
复制
 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,因此它是动态的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-26 12:16:30

如果您的useFetch钩子对更改有反应,那么..。

代码语言:javascript
复制
useFetch( img === "" ? defaultUrl : `https://api.unsplash.com/search/photos?page=1&query=${img}&client_id=${clientId}&per_page=20 `

或者对于更干净的代码,创建一个getUrl函数。

代码语言:javascript
复制
// 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()函数中添加条件检查

代码语言:javascript
复制
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))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74207561

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档