代码之家  ›  专栏  ›  技术社区  ›  JamesG

Redux中间件内部的功能不工作

  •  1
  • JamesG  · 技术社区  · 7 年前

    我正在尝试制作一些中间件,如果JWT过期,它会刷新我的JWT。我目前有这个中间件:

    import { isTokenExpired, refreshToken } from '../modules/auth/auth.service'
    export const jwt = store => next => action => {
        if (typeof action === 'function') {
          console.log("Middleware triggered:", action);
          var theState = store.getState();
          if (theState.auth && theState.auth.authToken && isTokenExpired(theState.auth.authToken)) {
            console.log('This is logging')
            //this function is not being called
            refreshToken(theState.auth.refreshToken);
          }
        }
        return next(action)
    }
    

    我希望调用refreshToken()函数来启动进程,但到目前为止,甚至可以调用控制台。refreshToken内的log()未调用:

    export const refreshToken = (refreshToken) => dispatch => {
      console.log('Not logging')
    }
    

    此外,refreshToken函数在刷新令牌时将是异步的。我想在reducer中设置一个“REFRESH\u TOKEN\u PENDING”类型,一旦收到响应,就向reducer发送“REFRESH\u TOKEN\u SUCCESS”。中间件可以做到这一点吗?

    谢谢

    1 回复  |  直到 6 年前
        1
  •  2
  •   Lucaci Sergiu    7 年前

    你必须这么做 refreshToken() 。如果您确实可以访问 dispatch() 进入 jwt 函数你应该这样称呼它 dispatch(refreshToken())

    考虑到我不确定你是如何触发 jwt公司

    // ================
    //  Container file
    // ================
    import {connect} from "react-redux";
    import { bindActionCreators } from "redux";
    // ... other 
    
    function mapActionsToProps(dispatch) {
      return bindActionCreators({
        jwt: path_to_actions_file.jwt
    }, dispatch)}
    
    const mapStateToProps = (state) => ({
      // ... your state properties
    });
    
    export default connect(mapStateToProps, mapActionsToProps)(YourComponent); // <== YourComponent has to be a React Component
    
    // ==============
    //  Actions file
    // ==============
    export const setConvertTypeActive = store => dispatch => {
      console.log('This is logging.');
      dispatch(refreshToken("md5Token"));
    }
    
    export const refreshToken = refreshToken => dispatch => {
      console.log('Should log now.');
    }
    

    关于最后一个问题,是的,你可以创建类似于 refreshToken 在减速器上设置某些状态的操作。检查以下代码:

    // ============== 
    //  Actions file
    // ==============
    export const refreshToken= {
      pending: () => ({
        // "REFRESH_TOKEN_PENDING"
      }),
      success: (data) => ({
        // "REFRESH_TOKEN_SUCCESS"
      })  
    };