Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

reactjs - React Router after reload always redirected to dashboard

i have one problem with react routers. It's my App class. I check my token, if it valid i do redirect to dashboard page.

class App extends Component {
constructor(props){
    super(props);
    this.checkAuth = this.checkAuth.bind(this);
}

checkAuth(){
    if(localStorage.getItem(ACCESS_TOKEN)){
        getCurrentAccount().then(response => {
            this.props.onLoadCurrentAccount({ account: response, isAuthenticated: true });
            this.props.history.push('/');
        });
    }
}

componentDidMount() {
    this.checkAuth();
}

render() {
    return (
        <div>
            <Switch>
                <Route path='/login' component={Login}/>
                <Route path='/signup' component={Signup} />
                <PrivateRoute authenticated={this.props.account.isAuthenticated} path='/' component={CoreLayout} />
                <Route component={NotFound}/>
            </Switch>
        </div>
    );
}

}

Here i have different routes to other components if you authorized. Always when i try to reload page i go to '/' page. For example: i stay on '/contacts' but when i reload page i go to '/'. How can i fix it?

class CoreLayout extends Component {
render() {
    return (
        <div>
            <Menu/>
            <Switch>
                <Route exact path='/' component={Dashboard}/>
                <Route path='/contacts' component={Contacts}/>
                <Route path='/assignment' component={Assignment}/>
                <Route path='/tasks' component={Tasks}/>
            </Switch>
        </div>
    );
}

}

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Due to your componentDidMount() Method;

In componentDidMount() method you are calling checkAuth() method in which you are using

this.props.history.push('/');

so try to change checkAuth() method as per your requirement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...