我有两个自定义挂钩,即 useFetch 和 useAuth。 useAuth 具有所有 API 调用方法(例如登录、注销、注册、getProfile 等),并且它们使用 useFetch 挂钩方法进行 API 调用。 useFetch 也使用这些方法,例如 API 返回 401 时的 logOut 方法、setToken 等。因此,它们都需要共享通用方法。但这会导致循环依赖和调用大小堆栈超出错误。如何管理这个
UseFetch.js
import React, { useState, useContext } from "react";
import { AuthContext } from "../context/authContext";
import { baseURL } from "../utils/constants";
import { useAuth } from "./useAuth";
const RCTNetworking = require("react-native/Libraries/Network/RCTNetworking");
export const useFetch = () => {
const {token, setAuthToken, isLoading, setIsLoading, logIn, logOut} = useAuth();
const fetchAPI = (method, url, body, isPublic, noBaseURL) => {
setIsLoading(true);
const options = {
method: method
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
};
return fetch(url, options, isRetrying).then(() => {
......
})
......
};
return { fetchAPI };
};
UseAuth.js
import React, { useContext, useEffect } from "react";
import { AuthContext } from "../context/authContext";
import { useFetch } from "./useFetch";
export const useAuth = () => {
const {
removeAuthToken,
removeUser,
setUser,
...others
} = useContext(AuthContext);
const { fetchAPI } = useFetch();
const register = (body) => {
return fetchAPI("POST", "/customers/register", body, true);
};
const logIn = (body) => {
return fetchAPI("POST", "/customers/login", body, true);
};
const logOut = () => {
return (
fetchAPI("POST", "/customers/logout")
.catch((err) => console.log("err", err.message))
.finally(() => {
removeAuthToken();
removeUser();
})
);
......
};
return {
...others,
register,
logIn,
logOut,
};
};
只需将
logOut
逻辑从 useAuth
带到您的 helpers
或 utils
。在 useAuth
的 logOut
方法和 useFetch
的 401 条件中使用该逻辑。由于logout
方法是useAuth
唯一需要的东西,你可以删除useAuth
钩子并使用useContext(AuthContext)
获得其他道具。