好吧,我厌倦了尝试.
该onEnter方法不起作用.知道为什么会这样吗?
// Authentication "before" filter
function requireAuth(nextState, replace){
console.log("called"); // => Is not triggered at all
if (!isLoggedIn()) {
replace({
pathname: '/front'
})
}
}
// Render the app
render(
<Provider store={store}>
<Router history={history}>
<App>
<Switch>
<Route path="/front" component={Front} />
<Route path="/home" component={Home} onEnter={requireAuth} />
<Route exact path="/" component={Home} onEnter={requireAuth} />
<Route path="*" component={NoMatch} />
</Switch>
</App>
</Router>
</Provider>,
document.getElementById("lf-app")
Run Code Online (Sandbox Code Playgroud)
编辑:
我打电话时执行该方法onEnter={requireAuth()},但显然这不是目的,我也不会得到所需的参数.
我正在使用React和React Router与Redux建立网站.许多路由(页面)需要登录.如果用户未登录,我可以重定向到登录:
function requireAuth(nextState, replace) {
let loggedIn = store.getState().AppReducer.UserReducer.loggedIn;
if(!loggedIn) {
replace({
pathname: '/login',
state: {
nextpathname: nextState.location.pathname
}
});
}
}
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Index} />
<Route path="login" component={Login} />
<Route path="register" component={Register} />
<Route path="dashboard" component={Graph} onEnter={requireAuth}>
... some other route requires logged in ...
</Route>
</Route>
</Router>
</Provider>,
document.getElementById('entry')
);
Run Code Online (Sandbox Code Playgroud)
如果用户没有登录,请查看代码,我使用onEnter挂钩重定向到'/ login'路由.用于检查用户登录的数据是在商店中,并且在用户登录后它将更新.
它工作得很好,但问题是当我刷新页面时,存储将被重置并且用户没有登录状态.
我知道这是因为Redux存储只是内存存储,所以refesh页面会丢失所有数据.
检查服务器会话每次刷新都可以工作,但这可能是太多的请求,所以这看起来不错.
将登录状态数据保存到localStorage可能有效,但在这种情况下,我应该检查每个AJAX调用失败该请求被拒绝,因为会话已过期或不存在像某些东西,这看起来也是个坏主意.
有没有办法更清楚地解决这个问题?我的网站将会使用很多人,所以我希望尽可能减少XHR呼叫.
任何建议将非常感谢.