重新加载后反应路由器总是重定向到仪表板 [英] React Router after reload always redirected to dashboard
问题描述
我对反应路由器有一个问题.这是我的应用程序类.我检查我的令牌,如果它有效,我会重定向到仪表板页面.
class App 扩展组件 {构造函数(道具){超级(道具);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();}使成为() {返回 (<div><开关><Route path='/login' component={Login}/><Route path='/signup' component={Signup}/><PrivateRoute authenticated={this.props.account.isAuthenticated} path='/' component={CoreLayout}/><路由组件={NotFound}/></开关>
);}
}
如果您授权,我在这里有到其他组件的不同路线.总是当我尝试重新加载页面时,我会转到/"页面.例如:我留在/联系人"上,但是当我重新加载页面时,我会转到/".我该如何解决?
class CoreLayout extends Component {使成为() {返回 (<div><菜单/><开关><路由精确路径='/' component={Dashboard}/><Route path='/contacts' component={Contacts}/><Route path='/assignment' component={Assignment}/><Route path='/tasks' component={Tasks}/></开关>
);}
}
谢谢
由于你的 componentDidMount()
方法;
在 componentDidMount()
方法中,您正在调用您正在使用的 checkAuth()
方法
this.props.history.push('/');
所以尝试根据您的要求更改 checkAuth()
方法.
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
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.
这篇关于重新加载后反应路由器总是重定向到仪表板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!