General route interceptors for react-router

时间:2015-12-14 18:00:08

标签: reactjs react-router refluxjs

Once a user logs in, they cannot continue until they complete their profile. If a user tries to navigate to a different page, I want to intercept them and redirect them back to the profile page as long as their profile is complete. Currently the best solution I came up with is:

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

While this does work, it seems incorrect in that you are supposed to return a valid component from render.

I have also tried doing this in componentWillMount and componentDidMount. This also works, but then you can see a flash of the other page get rendered before the redirect occurs.

This is a minor point but I also have to include this intercept on all pages that need to be intercepted rather than handle it through some configuration or a more generalized method.

Is there a preferred method for blocking/intercepting routes when using React views?

1 个答案:

答案 0 :(得分:1)

这个Lifecycle Mixin

怎么样?

routerWillLeave方法可以阻止路由

但是如果要在用户想要输入其他页面时在配置文件组件外部重定向,则可能需要在&lt; Route&gt;中添加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
    );
});