2015-12-14 139 views
0

一旦用戶登錄,他們無法繼續,直到他們完成他們的配置文件。如果用戶嘗試導航到其他頁面,我想攔截它們並將其重定向到配置文件頁面,只要其配置文件已完成即可。目前,我想出了最好的解決方案是:反應路由器的通用路由攔截器

render() { 
    if (!profileComplete()) { 
    return document.location.assign(document.location.origin + '/complete-prof')); 
    } 
    return <Page />; 
} 

雖然這個工作,它似乎是不正確的,你都應該從render返回一個有效組成部分。

我也試過在componentWillMountcomponentDidMount這樣做。這也可以,但是在重定向發生之前,你可以看到其他頁面的一個flash被渲染。

這是一個小問題,但我也必須在需要攔截的所有頁面上包含此攔截,而不是通過某種配置或更廣義的方法處理它。

當使用React視圖時,是否有阻止/攔截路由的首選方法?

回答

0

這個怎麼樣Lifecycle Mixin

的routerWillLeave方法可以阻止

,但如果你想在成型件的外重定向當用戶想進入其他頁面,則可能需要添加的OnEnter路線在<路線>標籤:onEnter of Route

// check login 
function auth(next, replace) { 
    let isLogin = Auth.isLogin(); 
    if (next.location.pathname === '/login' && isLogin) { 
     replace(null, '/'); 
    } else if (next.location.pathname !== '/login' && !isLogin) { 
     replace(null, '/login'); 
    } 
}; 
document.addEventListener('DOMContentLoaded', function() { 
    ReactDOM.render((
     <Router onUpdate={onPathChange} history={history}> 
      <Route path='/' component={App} onEnter={auth}> 
       <IndexRedirect to='index' /> 
       <Route path='index' component={Index} /> 
       <Route path="category" component={Category} /> 
       <Route path="attribute" component={Attribute} /> 
      </Route> 
      <Route path='login' component={Login} onEnter={auth} /> 
     </Router>), 
     appElement 
    ); 
}); 
+0

生命週期混入被棄用,因此,我寧可不使用它。一般來說Mixins似乎在React中皺起了眉頭。你能告訴我更多關於'在配置文件組件外部重定向'的含義嗎? –

+0

我的意思是在路由配置中設置重定向,就像上面的代碼一樣,它是一個檢查登錄重定向。在配置文件未完成時,將onEnter添加到您要重定向的路由。如果你想這樣做,你必須檢查組件外的配置文件完成。 –