将 redux 存储绑定到函数
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
来读取状态并发送一些动作,所以我不确定如何传递它。正如您在我的代码中看到的那样,我尝试使用绑定,但是 console.log(this)
returns 未在方法内部定义。
这是 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
做任何事情。这就是为什么你的控制台调用 returns 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)}
。
或者只使用普通函数。
我想将这些路由包装到 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
来读取状态并发送一些动作,所以我不确定如何传递它。正如您在我的代码中看到的那样,我尝试使用绑定,但是 console.log(this)
returns 未在方法内部定义。
这是 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
做任何事情。这就是为什么你的控制台调用 returns 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)}
。
或者只使用普通函数。