[英]Binding a redux store to a function
我將這些路徑包含在checkAuth
方法中,以查看訪問者的會話狀態。 為了保持代碼清潔,我將checkAuth
方法分離為一個單獨的文件,並將其導入帶有路由聲明的文件中:
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
讀取狀態並調度一些操作,所以我不確定如何傳遞它。 我嘗試使用bind,你可以在我的代碼中看到但是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;
....
};
您正在使用箭頭功能,因此您無法bind
任何內容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)}
。
或者只使用普通功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.