Javascript 基于组件的React路由器重定向';s州

Javascript 基于组件的React路由器重定向';s州,javascript,reactjs,Javascript,Reactjs,我想根据用户的登录状态重定向用户。在React路由器示例中,它们使用onEnter。但是,onEnter的功能无法访问组件的状态。在我的例子中,用户的登录状态存储在根组件中。如何根据根组件的状态重定向用户 例如,我的代码如下所示: ReactDOM.render(( <Router history={browserHistory}> <Route path="/" component={App}> <Route pat

我想根据用户的登录状态重定向用户。在React路由器示例中,它们使用
onEnter
。但是,
onEnter
的功能无法访问组件的状态。在我的例子中,用户的登录状态存储在根组件中。如何根据根组件的状态重定向用户

例如,我的代码如下所示:

ReactDOM.render((
    <Router history={browserHistory}>
        <Route path="/" component={App}>
            <Route path="login" component={PageLogin}/>
            <Route component={PageAuth}>
                <IndexRoute component={PageHome}/>
                ...
            </Route>
        </Route>
    </Router>
), document.getElementById('react'));
在PageAuth中:

class PageAuth extends React.Component {
    constructor(props) {
        super();

        if (!props.state.user.id) {
            ReactRouter.browserHistory.push('/login');
        }
    }
    ...
};

这将按预期重定向,但我得到了警告:setState(…):无法在现有状态转换期间更新(例如在“render”中)。渲染方法应该是道具和状态的纯函数。。我假设我不应该在构造函数中重定向。是否有更好的方法来执行此操作?

导致警告的可能不是重定向,而是渲染方法中尝试执行设置状态的内容。更好的重定向方法是检查componentDidMount或componentWillReceiveProps方法中的
props.state.user.id
。我尝试更改渲染方法以仅返回
,但错误仍然发生。您知道componentDidMount或componentWillReceiveProps是首选吗?是的,它更首选,因为您可以通过比较componentWillReceiveProps中的this.props和nextProps轻松检查现有或将要接收的道具。不过,我通常会检查这两种方法,以确定是否存在用户不必在该组件中进行身份验证的状态
class PageAuth extends React.Component {
    constructor(props) {
        super();

        if (!props.state.user.id) {
            ReactRouter.browserHistory.push('/login');
        }
    }
    ...
};