关于useHttp的get请求问题

来源:7-2 用高级 Hook-useAsync统一处理Loading和Error状态

詹姆士郭德纲

2021-06-28

在这里输入代码
//这是老师的源码
export const http = async (
  endpoint: string,
  { data, token, headers, ...customConfig }: Config = {}
) => {
  const config = {
    method: "GET",
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
      "Content-Type": data ? "application/json" : "",
    },
    ...customConfig,
  };

  if (config.method.toUpperCase() === "GET") {
    endpoint += `?${qs.stringify(data)}`;
  } else {
    config.body = JSON.stringify(data || {});
  }

  // axios 和 fetch 的表现不一样,axios可以直接在返回状态不为2xx的时候抛出异常
  return window
    .fetch(`${apiUrl}/${endpoint}`, config)
    .then(async (response) => {
      if (response.status === 401) {
        await auth.logout();
        window.location.reload();
        return Promise.reject({ message: "请重新登录" });
      }
      const data = await response.json();
      if (response.ok) {
        return data;
      } else {
        return Promise.reject(data);
      }
    });
};

data不管传没传 endpoint后面都会加?吧
不用添加判断吗

写回答

2回答

mailtohc

2021-09-06

url += qs.stringify(cleanQueryStringObject(data ?? {}), { addQueryPrefix: true })

把之前那个地方改成这样就可以了, qs的第二个参数加一个addQueryPrefix

0
0

Nolan

2021-06-28

这个确实可以优化,如果data不存在就不传问号

0
0

React17+Hook+TS4 优质实践,仿 Jira 企业级项目

解锁 React17 高阶用法,轻松应对大型复杂长周期项目

2691 学习 · 1236 问题

查看课程