2017-07-20 27 views
0

我想讓一些中間件刷新我的JWT,如果它已經過期了。目前,我有這個中間件:Redux中間件內部的函數不能正常工作

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」。這對中間件來說可能嗎?

感謝

回答

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動作的中間件來設置reducer的一些狀態。請檢查以下代碼:

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