2017-03-01 61 views

回答

1

您可以使用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

相關問題