在 axios 中设置 headers 并做出反应时出错

Error in setting headers in axios and react

我已经尝试了很多堆栈溢出的解决方案,但我无法解决这个问题

我的代码如下

helper/axios.js

import axios from "axios";

const instance = axios.create({
  baseURL: process.env.REACT_APP_BACKEND_URI,
  timeout: 1000,
  headers: {},
});

export default instance;

App.js

import axios from "./helper/axios";
 
const { user } = useAppSelector((state) => state);

axios.interceptors.request.use((config: any) => {
    if (user.isLoggedIn) {
      config.headers.authorization = user.accessToken;
      config.headers["x-refresh"] = user.refreshToken;
      console.log(config);
    }
    return config;
  });

[控制台图片] [1]: https://i.stack.imgur.com/fWAIb.png

也许您可以尝试将 store 直接导入到文件中。

我不认为 useSelector 可以在功能组件之外调用。

示例,

import axios from "./helper/axios";
import store from "./your_path_to_store_file"

axios.interceptors.request.use((config: any) => {
    const { user } = store.getState();
    if (user.isLoggedIn) {
      config.headers.authorization = user.accessToken;
      config.headers["x-refresh"] = user.refreshToken;
      console.log(config);
    }
    return config;
});

这样做,我们可能会从商店获得最新的价值。