通用路由器的'onEnter'挂钩

时间:2017-03-01 10:07:16

标签: reactjs react-router

使用React Router,当某个条件使用onEnter()挂钩符合时,您可以中止转换或重定向到其他路由。

是否有Universal Router的等效功能,以便我可以侦听路由更改并将用户重定向到其他页面(例如,访客用户的登录页面)?

1 个答案:

答案 0 :(得分: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