【问题标题】:Function inside of Redux middleware not workingRedux 中间件内部的功能不起作用
【发布时间】:2017-07-20 21:10:38
【问题描述】:

我正在尝试制作一些中间件,如果它过期了,它会刷新我的 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 内的 console.log() 也没有调用:

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

此外,refreshToken 函数内部在刷新令牌时将是异步的。我正在考虑在减速器中设置“REFRESH_TOKEN_PENDING”类型,一旦收到响应,将“REFRESH_TOKEN_SUCCESS”发送到减速器。中间件可以做到这一点吗?

谢谢

【问题讨论】:

    标签: reactjs redux middleware redux-thunk


    【解决方案1】:

    您必须发送 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"
      })  
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      • 2014-02-21
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 2021-01-16
      相关资源
      最近更新 更多