【发布时间】:2018-02-20 10:41:54
【问题描述】:
我想将我的应用程序的某些部分限制为仅限登录用户。 我使用下面的代码进行这项工作。
但是,以前我使用 Switch 路由器在找不到匹配的路由时将用户发送到 404 页面。
由于某种原因,自从我将 EnsureLoggedIn 组件添加到 App.jsx 后,用户永远不会被重定向到 404 页面。
测试:在 URL 中输入的随机路径。应该路由到 404 页面。
- isLoggedIn=false :用户被定向到 /login 页面。
- isLoggedIn=true :找不到匹配的路由,页面容器呈现为空。
我希望交换机路由器忽略嵌套在 EnsureLoggedIn 中的内容,因为没有任何路由匹配,然后呈现 404。
希望有更多 React 经验的人可以指导我。
App.jsx
<BrowserRouter>
<Header/>
<Switch>
<Route exact path="/" component={HomePage}/>
<Route exact path="/someotherpage" component={SomeOtherPage}/>
<EnsureLoggedIn>
<Route exact path="/dashboard" component={Dashboard}/>
</EnsureLoggedIn>
<Route component={Error404Page}/>
</Switch>
<Footer/>
</BrowserRouter>
EnsureLoggedIn.jsx
class EnsureLoggedIn extends Component {
constructor(props) {
super(props);
this.state = {isLoggedIn: false};
}
render() {
const isLoggedIn = this.state.isLoggedIn;
if (isLoggedIn) {
return this.props.children
} else {
return ( <Redirect to="/login" /> );
}
}
}
【问题讨论】:
标签: reactjs react-router