2016-06-20 27 views
2

我已經花了大約1周閱讀在REDX之前陷入任何可觀的大小。在完成大部分的教程後,我已經做了,我意識到,好的。我理解終極版,但是到底如何我做一個複雜的系統:P使用中間件來檢查用戶會話反應減少

我剛入有關創建我的系統操作:

function requestLogin(creds) { 
    return { 
     type: LOGIN_REQUEST, 
     isFetching: true, 
     isAuthenticated: false, 
     creds 
    } 
} 

function receiveLogin(user) { 
    return { 
     type: LOGIN_SUCCESS, 
     isFetching: false, 
     isAuthenticated: true, 
     id_token: user.id_token 
    } 
} 

function loginError(message) { 
    return { 
     type: LOGIN_FAILURE, 
     isFetching: false, 
     isAuthenticated: false, 
     message 
    } 
} 

但是,如何在使用每個路由器(使用react-router)後檢查用戶是否在將用戶登錄狀態存儲爲redux狀態後是否有會話?

我想創建一些能夠在每個視圖中執行的東西。只需簡單地在每個視圖中編寫一個函數exec()

回答

3

是的,你創建一個函數,當你去一個需要登錄的路由時執行。

import LoginActions from '../loginActions'; 

const requireLogin = (nextState, replace) => { 
    store.dispatch(LoginActions.CheckLogin()); 
    const {login} = store.getState(); 
    if (!login.isAuthenticated) 
    replace('/login'); 
}; 

調用它在你的路由器:

<Router component={Root}> 
<Route path="/dashboard" onEnter={requireLogin} component={dashboard}/> 
</Router> 
+0

尼斯一個隊友:)我覺得很奇怪,但因爲'CheckLogin'行動從字面上去是一條線嗎? '輸入:LOGIN_CHECK'例如哪個會觸發reducer? –

+0

是的。您也可以通過刷新頁面將您的登錄令牌放入cookie/localstorage中進行持久保存,並在CheckLogin()操作中檢查令牌。 – jzm

+0

我在這些句子中用了太多次:D Cheers pal –

1

您可以實現身份驗證過濾器用於需要使用高階組件認證的用戶路徑。

創建包裝組件

import React from 'react'; 
import { connect } from 'react-redux'; 
export default function(ComposedComponent) { 
    class AuthFilter extends React.Component { 
     // triggered when component is about to added 
     componentWillMount() { 
      if (!this.props.userAuthenticated) { 
       console.log("navigate to login"); 
       this.context.router.push('/login'); 
      } 
     } 
     // before component updated 
     componentWillUpdate(nextProps) { 
      if (!nextProps.userAuthenticated) { 
       console.log("navigate to login"); 
       this.context.router.push('/login'); 
      } 
     } 
     render() { 
      return <ComposedComponent {...this.props} /> 
     } 
    } 
    AuthFilter.contextTypes = { 
     router: React.PropTypes.func.isRequired 
    } 
    function mapStateToProps(state) { 
     return { userAuthenticated: state.authenticated }; 
    } 
    return connect(mapStateToProps)(AuthFilter); 
} 

然後放入包裝內,以你的路線組件爲:

Route path="/asset" component={AuthFilter(AssetRoute)}/> 
相關問題