这是我的路由器结构:
<Router>
<div>
<Route path="/" exact component={ Login } />
<Route path="/timeline" component={ requireAuth(Timeline) } />
<Route path="/chat/:id" component={ requireAuth(Chat) }/>
</div>
</Router>
requireAuth()是一个简单的高阶组件,它会进行API调用并基于响应渲染<ComposedComponent {...this.props} />
或<Redirect to="/" />
我面临两个问题:
- 每当我从/timeline到/chat/XXX时,都会调用requireAuth()
- 当我从/timeline到/chat/XXX时,浏览器重新加载页面。
我该如何解决这个问题?我想我应该以某种方式包装需要身份验证的路由?...
更新
所以我花了一些时间,想出了以下逻辑:
ReactDOM.render((
<div>
<Router>
<Switch>
<Route exact path="/" component={Login} />
<App>
<Route path="/timeline" component={Timeline} />
<Route path="/chat/:id" component={Chat} />
</App>
</Switch>
</Router>
</div>
), document.getElementById('root'))
我的认证逻辑现在存储在App.js中,并且仅在我尝试打开<App></App>
部分内的任何路由时调用一次。