如何使用通用函数处理多个useeffect挂钩调用以管理唯一状态

时间:2020-10-14 07:10:39

标签: reactjs react-native react-hooks

我有一个通用的useeffect函数来处理ajax调用,如下所示: 请忽略其他内容,仅关注useEffect和useState,而我希望从同一组件调用时状态有所不同。请参考以下功能:

$(selector).load(url);
$(selector).load(url);

我多次在组件中调用此函数

export const useFetch = (
  url: string,
  loaderArea: string = areas.main,
  requestType: HttpReqestType = HttpReqestType.GET,
  options?: any,
  depArr: React.DependencyList = []
) => {
  const [response, setResponse] = React.useState<any>(null);
  const [error, setError] = React.useState<any>(null);
  React.useEffect(() => {
    const fetchData = async () => {
      try {
        await trackPromise(delay(200), loaderArea);
        let result = null;
        if (requestType === HttpReqestType.GET) {
          result = await trackPromise(
            API.get(url).then(response => {
              if (response.status === 200 && !!response.data) {
                return response.data;
              } else {
                console.error(url,response)
                return null;
              }
            }),
            loaderArea
          );
        } else if (requestType === HttpReqestType.POST) {
          result = await trackPromise(
            API.post(url, options).then(response => {
              return response.data;
            }),
            loaderArea
          );
        }
        setResponse(result);
      } catch (error) {
        setError(error);
      }
    };
    fetchData();
  }, depArr);
  return { response, error };
}

由于状态或useState(方法响应和错误)重复,我有多个渲染错误 如何处理这些状态,以便我可以多次调用而不会出错?

0 个答案:

没有答案