1
通過React Router
,您可以使用onEnter()
掛鉤在某個條件滿足時中止轉換或重定向到其他路由。通用路由器的'onEnter'鉤子
Universal Router
是否有任何等效功能,以便我可以偵聽路由更改並將用戶重定向到其他頁面(例如,訪客用戶的登錄頁面)?
通過React Router
,您可以使用onEnter()
掛鉤在某個條件滿足時中止轉換或重定向到其他路由。通用路由器的'onEnter'鉤子
Universal Router
是否有任何等效功能,以便我可以偵聽路由更改並將用戶重定向到其他頁面(例如,訪客用戶的登錄頁面)?
您可以使用history,然後檢查路由的action
中的情況,這幾乎等同於react-router的onEnter
。這裏有一個例子:
// Indicator if user is logged in or not.
// const USER = { name: 'Eric' };
const USER = null;
// Create browser history.
const history = window.History.createBrowserHistory();
// Set up routes.
const routes = [
{
path: '/settings',
action: context => {
// If the user is signed in, show settings, otherwise redirect to login.
if (!USER) history.push('/login');
return <h1>Private Settings for {USER.name}</h1>;
}
},
{ path: '/login', action:() => <h1>Login</h1> },
{ path: '*', action:() => <h1>Not Found</h1> }
];
// Listen to route changes, re-render with Universal Router when needed.
const unlisten = history.listen((location, action) => {
UniversalRouter.resolve(routes, {
path: location.pathname
}).then(component => {
ReactDOM.render(component, document.getElementById('root'));
});
});
// Go to settings on default.
history.push('/settings');
對JSBin。