我创建了一个自定义中间件,它调用一个类方法来向所有 axios 请求添加授权标头,但是当这个钩子尝试使用useSelector
钩子从状态中选择数据时,我得到一个错误。
Invalid hook call. Hooks can only be called inside of the body of a function component
如何从此中间件获取处于状态的 accessToken 存储?
中间件.ts
import { Dispatch } from 'react';
import { AnyAction, Middleware, MiddlewareAPI } from 'redux';
import { authManager } from 'src/features/auth/authManager';
import { authActions } from 'src/features/auth/redux';
import { RootState } from '.';
export const setIsAxiosAuthorized: Middleware = (api: MiddlewareAPI) => (
next: Dispatch<AnyAction>
) => (action) => {
authManager.setAxiosAuthorizationToken();
api.dispatch(authActions.setIsAxiosAuthorized(true));
return next(action);
};
authManager.ts
import axios from 'axios';
import authService from './authService';
import { useAuth } from './hooks';
let axiosInstance = axios.create();
class AuthManager {
constructor() {
axiosInstance.interceptors.response.use(
(response) => response,
async (error) => {
if (error?.response?.status === 401) {
return Promise.resolve();
}
return Promise.reject(error);
}
);
}
getAxiosInstance = () => axiosInstance;
resetAxiosInstance = () => {
axiosInstance = axios.create();
};
getAccessToken = authService.getAccessToken;
setAxiosAuthorizationToken = () => {
const { accessToken } = useAuth();
axiosInstance.interceptors.request.use(
(config) => {
let headers = config.headers ? { ...config.headers } : {};
headers = {
...headers,
Authorization:
accessToken !== undefined ? `Bearer ${accessToken}` : '',
};
config.headers = headers;
return config;
},
(error) => Promise.reject(error)
);
};
}
export const authManager = new AuthManager();