【问题标题】:React access redux store in axios interceptor在 axios 拦截器中反应访问 redux 存储
【发布时间】:2021-11-07 17:16:12
【问题描述】:

我想在配置 jwt 令牌的 axios 拦截器中访问 redux 存储,所以我将存储导入到 API.js 文件中。但它立即注销了一些错误。

这是 axios 实例

import axios from "axios";
import { store } from '../redux/store';

export const SERVERURL = "some url";

axios.defaults.withCredentials = true;
const API = axios.create({ baseURL: "some url" });

API.interceptors.request.use(req => {
  // something I want to do
  return req;
});

export default API;

这里是 store.js

import { configureStore } from "@reduxjs/toolkit";
import userReducer from "./user";

export const store =  configureStore({ reducer: { user: userReducer } });

还有 index.js

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import "./index.css";
import App from "./App";
import {store} from "./redux/store";
import { Provider } from "react-redux";

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById("root")
);

我想知道会是什么问题?

【问题讨论】:

  • 它不相关,您必须对请求的user 密钥有其他问题。你导入store的方式是正确的。
  • 你能分享./user文件吗?
  • userReducer 有问题

标签: reactjs redux axios


【解决方案1】:

这是一个循环导入依赖问题,由尝试将store 文件直接导入代码库的其他部分引起。您需要避免这样做。

根据我们的文档,一个推荐的选项是在 Axios 拦截器文件中添加一个小的 setStore() 函数,并将 store 作为应用程序设置的一部分注入拦截器 index.js:

https://redux.js.org/faq/code-structure#how-can-i-use-the-redux-store-in-non-component-files

【讨论】:

    猜你喜欢
    • 2018-09-12
    • 2018-11-27
    • 2021-07-04
    • 2019-02-11
    • 2020-07-20
    • 2017-05-28
    • 2021-10-03
    • 2017-09-17
    • 1970-01-01
    相关资源
    最近更新 更多