我是新來反應和學習如何作出反應 - 路由器實現路由。作爲我的示例應用程序的一部分,我試圖在每個作爲網站一部分的路徑上添加一個身份驗證器。我下面這個例子:https://github.com/reactjs/react-router/blob/master/examples/auth-flow/app.js反應路由器和身份驗證
這裏是我的示例代碼:
render(
<Router history={browserHistory}>
<Route path="/" component={App} onEnter={requireAuth}>
<IndexRoute component={Home}/>
<Route path="login" component={Login}/>
<Route path="logout" component={Logout}/>
<Route path="about" component={About}/>
<Route path="inbox" component={Inbox}/>
</Route>
</Router>,
document.getElementById("app"));
這裏是什麼requireAuth做:
function requireAuth(nextState, replace) {
if(!auth.isUserLoggedIn()) {
replace({
path: "/login",
state: {nextPathname: nextState.location.pathname}
});
}
}
之間的區別是什麼我做什麼該示例確實是該示例僅將auth功能放在一個路由(儀表板)上,因爲我希望將它放在每條路由上。但這個例子停止工作,並開始拋出錯誤說:「最大調用堆棧大小超出」,我認爲是正確的,因爲/登錄是/的子路由,因爲requireAuth重定向到子路由,它只是嘗試再次驗證,並繼續嘗試永遠。我可能在這裏錯過了一個簡單的解決方法來實現這個目標,但我無法確定什麼是最好的方法。我能做些什麼來在網站的每個級別啓用身份驗證?
謝謝,我也看到了這個例子。但正如我在我的問題中提到的那樣,我想讓每條路徑都可以在訪問之前進行身份驗證。因此,需要在每條路線上啓用它(試圖避免明確地將onEnter方法放在登錄以外的每個路線上)。 – KumarM