且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

reactjs axios 拦截器如何调度注销操作

更新时间:2023-12-04 17:31:40

您可以将此拦截器代码包含在您可以直接访问 redux 存储的同一位置.也许在您创建 redux 存储 (index.js) 的文件中?

You could include this interceptor code in the same place you have access to the redux store directly. Maybe in the file that you create your redux store (index.js)?

有了它,你就可以像这样直接从 redux store 分派动作:

With that in place, you can dispatch the action directly from the redux store like that:

import reduxStore from './store';

import App from './components/App';

const router = (
  <Provider store={reduxStore}>
    <Router>
      <Route path="/" component={App}/>
    </Router>
  </Provider>
);

/** Intercept any unauthorized request.
* dispatch logout action accordingly **/
const UNAUTHORIZED = 401;
const {dispatch} = reduxStore; // direct access to redux store.
axios.interceptors.response.use(
  response => response,
  error => {
    const {status} = error.response;
    if (status === UNAUTHORIZED) {
      dispatch(userSignOut());
    }
   return Promise.reject(error);
 }
);

render(router, document.getElementById('app-root'));