art*_*snr 6 circular-dependency reactjs react-native react-hooks
我有两个自定义挂钩,即useFetch和useAuth。useAuth具有所有 API 调用方法(例如 logIn、logOut、register、getProfile 等),并且它们使用useFetch钩子方法进行 API 调用。useFetch也使用这些方法,例如 API 返回 401 时的 logOut 方法、setToken 等。因此,它们都需要共享通用方法。但这会导致循环依赖和调用大小堆栈超出错误。如何管理这个
使用Fetch.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 };
};
Run Code Online (Sandbox Code Playgroud)
使用Auth.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,
};
};
Run Code Online (Sandbox Code Playgroud)
小智 0
只需将logOut逻辑从useAuth带到您的helpers或即可utils。在useAuth的logOut方法和useFetch401 条件中使用该逻辑。由于logoutmethod 是 中唯一需要的东西useAuth,因此您可以删除useAuth钩子并使用useContext(AuthContext)来获取其他道具。
| 归档时间: |
|
| 查看次数: |
1115 次 |
| 最近记录: |