React Router:browserHistory.push()不能正常工作

时间:2017-09-24 18:31:52

标签: reactjs react-router

我有一个函数 checkAuth 我想在输入'/ home'之前触发它。我正在使用react-router 2.6.0

我的代码(相关部分)看起来像这样 -

import React from 'react';
import {Route, IndexRoute, browserHistory, IndexRedirect} from 'react-router';
import Layout  from './Layout.jsx';
import HomePage from './HomePage.jsx';
import AuthPage from './AuthPage.jsx';

function checkAuth(){
    if(localStorage.getItem('auth')!='true'){
        console.log('inside'); // this is getting called
        browserHistory.push("/auth");
    }

}

const routes=(
    <Route path="/" component={Layout}>
        <IndexRedirect to="/home" />
        <Route path="/home" component={HomePage} onEnter={checkAuth} />
        <Route path="/auth" component={AuthPage} />
    </Route>
);

export default routes;

现在问题是它在控制台中打印'内部'并且网址从'/ home'更改为'/ auth'但在布局内部,我得到主页组件而不是验证(在当前情况下需要)组件。

我的布局组件 -

import React from 'react';

class Layout extends React.Component{

    constructor(props){
        super(props);
    };

    render(){
        return(
            <div>
                <div id="container">{this.props.children}</div>
            </div>
        );
    }

}

export default Layout;

我也试过browserHistory.replace('/auth'),但这对我没有帮助。

我遵循了link,这表明在 Home 组件呈现后,布局组件可能无法呈现 Auth 组件。

但我需要更多关于这个问题的见解。也是解决方案的任何方法。

感谢。

0 个答案:

没有答案