最近,我已经尝试通过React构建一个Web平台。一切正常,一切正常。但是,当我尝试为用户登录创建其他页面时,我遇到了很多问题:
我的代码中已经有Routes,所以当我尝试将其他Routes添加到另一个js文件时,它们根本无法工作。
我不知道如何在React Router中进行身份验证,我已经尝试了很多方法,遵循了许多教程,但是没有解决。
<Switch>
<Route exact path='/' component={Feed}/>
<Route path="/user" component={Profilo}/>
<Route path='/explore-page' component={ExplorePage} />
<Route path='/events-page' component={EventsPage} />
<Route path='/calendar-page' component={CalendarPage} />
<Route path='/stats-page' component={StatsPage} />
<Route path='/form' component={FormPage}/>
<Route path="/user" component={Profilo}/>
<Route path="/user/:userId" component={Profilo} />
</Switch>
这是我目前在div中使用的所有路线,用于渲染react组件。正如我之前所说,在上层文件中添加其他路由不会给我任何响应。
所以,最后,我要问你应该在哪里放置登录名和住所的路线?还是在那里应该移动所有内容?
谢谢你。
一种简单的方法是在渲染函数中添加用于处理身份验证的逻辑。
如果用户未通过身份验证。重定向到登录页面。否则,请转到您的组件
render() {
if (!this.props.isAuth) {
return (
<Switch>
<Route exact path="/" component={Login} />
<Redirect to="/" />
</Switch>
);
}
return (<Switch>
<Route
// your router
/>
</Switch>);
}