【发布时间】:2018-10-24 18:00:59
【问题描述】:
我是 react-router(以及一般的客户端路由)的新手,所以我可能认为这一切都错了。如果是这种情况,请提前道歉......
基本上只想实现3个简单的规则:
- 如果没有用户,重定向到'/login'
- 否则,如果路由不存在,则重定向到“/”(根目录)
- 否则让用户转到请求的路线
我在this.state.user 中跟踪用户。我当前的路由器似乎遵循前 2 条规则,但只让经过身份验证的用户看到主页('/profile' 重定向到 '/'),所以我知道我做错了什么,但不知道是什么。
<Router>
{this.state.user ? (
<Switch>
<Route path="/" exact component={Home}/>
<Route path="/profile" exact component={Profile}/>
<Route render={() => (<Redirect to="/" />)}/>
</Switch>
) : (
<Switch>
<Route path="/login" exact component={Login}/>
<Route render={() => (<Redirect to="/login" />)}/>
</Switch>
)}
</Router>
感谢任何建议。谢谢
【问题讨论】:
-
如果找不到路由,您可以简单地尝试
重定向到根(即 Home)组件吗? -
我在代码沙箱中尝试了相同的代码,并按预期访问了 /profile。请检查链接codesandbox.io/s/n422y545pl
-
Switch中不需要添加Redirect组件。您必须在希望用户登录的每个组件中设置条件渲染,即您检查用户是否已登录以查看路线,如果没有。然后渲染 react-router-dom 提供的 Redirect 组件。
-
@RahilAhmad 感谢您提供的示例。让我意识到路由发生在用户状态设置之前。
标签: reactjs authentication routing react-router react-router-v4