redux 中如何进行路由跳转

2,808 阅读1分钟

项目前期为了开发方便,前端接口调用没有做登录验证。cookie 过期后后台无法正常返回数据,导致界面为空,偶尔还会出现一些堆栈错误信息。解决这个问题最直观的想法是在每次请求数据的时候判断响应数据状态码,如果这样那代码改动量有点大(请求数据代码分散在不同的文件中)且会产生重复判断状态码的代码。 最后选择在 axios 中拦截并处理后台返回数据状态码。对于未登录的情况,提示用户登录并自动跳转到登录页。那么如何在 redux 中( axios 的代码写在 redux 的 actions 中)进行路由跳转呢,下面提供一种参考代码。

1、首先安装插件

yarn add history react-router-redux

2、封装请求,使用插件

// store.js
import { createStore, combineReducers, applyMiddleware } from  'redux';
import { routerMiddleware } from  'react-router-redux';
import { createHashHistory } from  'history';
import  thunk  from  'redux-thunk';
import  reducers  from  './reducers';

export  default  createStore(
  combineReducers(reducers),
  applyMiddleware(thunk, routerMiddleware(createHashHistory())),
);

3、拦截请求,调用插件

import  Axios  from  'axios';
import { push } from  'react-router-redux';
import  store  from  './store';

const  axios  =  Axios.create({
  baseURL:  '',
  timeout:  3600,
  withCredentials:  true,
});

axios.interceptors.response.use(
  (response) => { 
    const  res  =  response.data;   
    if (res.code  !==  200) { store.dispatch(push('/login')); }   
    return  res;
  }, (error) =>  Promise.reject(error.response.data),
);