onreadystatechange / blogs

主要记录项目中的重难点,以及如何攻克,有一定的借鉴意义,主要写在Issues
3 stars 0 forks source link

写一个Redux MiddleWare #2

Open onreadystatechange opened 5 years ago

onreadystatechange commented 5 years ago

authMiddleware主要用于过滤失败的action,并通过判断状态码触发一些副作用

onreadystatechange commented 5 years ago
import {push} from "react-router-redux";
import {unAuth, LOGIN_FAIL} from "./modules/userAuth";
const defaultTypeSuffixes = ['SUCCESS', 'FAIL']

export default function authMiddleware(config = {}) {
  const promiseTypeSuffixes = config.promiseTypeSuffixes || defaultTypeSuffixes

  return ({dispatch, getState}) => next => action => {

    if (action.type) {
      //定义失败与成功的变量值
      const [SUCCESS, FAIL] = promiseTypeSuffixes
      //正则判断
      const isSuccess = new RegExp(`${SUCCESS}$`, 'g')
      const isFail = new RegExp(`${FAIL}$`, 'g')
      var unLogined = false;

      if (action.type.match(isSuccess)) {
         //判断状态码
        if (action.data && action.data.code == -2) {
          unLogined = true;
        }
      } else if (action.type.match(isFail)) {
         //判断状态码
        if (action.error && action.error.code && action.error.code == -2) {
          unLogined = true;
        }
      }
      //登录失效切action type不为登录失败状态 执行路由自动跳转 
      if (unLogined && action.type != LOGIN_FAIL) {
        const state = getState();
        const url = state && state.routing && state.routing.locationBeforeTransitions && state.routing.locationBeforeTransitions.pathname;
        dispatch(unAuth());
        //将用户前一次访问地址编码并拼接在url中,再次登录成功后跳转至原网页
        dispatch(push("/login" + ((url && url != '/login') ? "?url=" + encodeURIComponent(url) : "")));
      }
    }
    //执行下一个中间件
    return next(action)
  }
}