2016-03-13 44 views
2

我有這些路線,我想包裹到checkAuth方法來查看訪問者的會話狀態。爲了保持代碼的乾淨我隔了checkAuth方法到一個單獨的文件,並將其導入與路線聲明文件:綁定一個REDX存儲到函數

import {checkAuth} from 'helpers/core' 

export default (store) => { 
    return (
     <Router history={browserHistory} onEnter={checkAuth.bind(store)}> 
      <Route path={AUTH_ROUTE} component={AuthLayout}> 
       <IndexRoute component={AuthView}/> 
      </Route> 

      <Route component={CoreLayout}> 
       <Route path={DASHBOARD_ROUTE} component={AuthView}/> 
      </Route> 
     </Router> 
    ) 
} 

checkAuth需要store閱讀狀態,也派遣了一些行動,所以我不確定如何交上來。我嘗試使用綁定,因爲您可以在我的代碼中看到,但console.log(this)在方法內返回undefined。

這裏的checkAuth代碼:

export const checkAuth = (desiredRoute, redirect) => { 
    console.log(this);// returns undefined 
    const state = this.getState();// Cannot read property 'getState' of undefined 
    const isAuthenticated = state.auth.loggedIn; 
    .... 
}; 
+0

是什麼阻止你在'checkAuth'模塊中要求'store'? – Oleg

+0

'onEnter'不應該調用函數,所以我不能將括號放在那裏,只需將store作爲參數。 –

回答

3

您使用箭頭功能,所以你不能bind任何東西給他們。這就是您的控制檯調用返回undefined的原因。

您可以直接導入存儲您的checkAuth模塊:

import store from 'path/to/store'; 
export const checkAuth = (desiredRoute, redirect) => { 
    const state = store.getState(); 
} 

,簡單地把它作爲onEnter={checkAuth}

也可以使工廠:

export const checkAuth = (store) => (desiredRoute, redirect) => { 
    const state = store.getState(); 
} 

,並通過它的商店:onEnter={checkAuth(store)}

或者只是使用普通功能。

+0

謝謝。從你的答案中學到了一些新東西:你不能綁定到箭頭函數和工廠。 –

相關問題