Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

写一个Redux MiddleWare #2

Open
onreadystatechange opened this issue Apr 10, 2019 · 1 comment
Open

写一个Redux MiddleWare #2

onreadystatechange opened this issue Apr 10, 2019 · 1 comment

Comments

@onreadystatechange
Copy link
Owner

onreadystatechange commented Apr 10, 2019

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

@onreadystatechange
Copy link
Owner Author

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)
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant