axios 拦截器中的 useContext [英] useContext inside axios interceptor

查看:53
本文介绍了axios 拦截器中的 useContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么我的 useContext 没有在这个函数中被调用:

I cant figure out why my useContext is not being called in this function:

import { useContext } from "react";
import { MyContext } from "../contexts/MyContext.js";
import axios from "axios";

const baseURL = "...";

const axiosInstance = axios.create({
  baseURL: baseURL,
  timeout: 5000,
.
.
.
});
axiosInstance.interceptors.response.use(
  (response) => response,
  async (error) => {
    const { setUser } = useContext(MyContext);
    console.log("anything after this line is not running!!!!");
    setUser(null)

.
.
. 

我的目标是使用拦截器来检查令牌是否有效,是否未清除用户并进行登录.我在其他 React 组件中使用相同的上下文.它在那里工作正常,只是没有在这里运行!知道我做错了什么吗?

My goal is to use an interceptor to check if the token is live and if its not clear the user and do the login. I'm using the same context in my other react components. And its working fine there, its just not running here! any idea whats I'm doing wrong?

推荐答案

我遇到了和你一样的问题.我是这样解决的:

I had the same issue as you. Here is how I solved it:

您只能在功能组件中使用 useContext 这就是为什么您不能在 axios 拦截器中执行 setUser 的原因.

You can only use useContext inside a functional component which is why you can't execute setUser inside your axios interceptors.

您可以做的是创建一个名为 WithAxios 的单独文件:

What you can do though is to create a separate file called WithAxios:

// WithAxios.js

import { useContext, useMemo } from 'react'
import axios from 'axios'

const WithAxios = ({ children }) => {
    const { setUser } = useContext(MyContext);

    useMemo(() => {
        axios.interceptors.response.use(response => response, async (error) => {
            setUser(null)
        })
    }, [setUser])

    return children
}

export default WithAxios

然后在 MyContext.Provider 之后添加 WithAxios 以访问您的上下文,例如:

And then add WithAxios after MyContext.Provider to get access to your context like this for example:

// App.js

const App = () => {
    const [user, setUser] = useState(initialState)

    return (
        <MyContext.Provider value={{ setUser }}>
            <WithAxios>
                {/* render the rest of your components here  */}
            </WithAxios>
        </MyContext.Provider>
    )
}

这篇关于axios 拦截器中的 useContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆