reactjs - 用单独的页面反应包罗万象
问题描述
我看到了很多关于如何在 SPA 中创建找不到页面的路由的解决方案,但似乎无法为也使用单独页面(如登录)的 SPA 找到任何东西。
例如:
<Router>
<Switch>
<Route path="/login" component={Login} />
<Route path="/" component={Main} />
** a catch all route wouldn't work here **
</Switch>
</Router>
包罗万象的路线不能在上面使用类似的东西,<Route component={NotFound} />
因为 path 会在任何来自path='/'
. 如果切换到exact path='/'
,则无法localhost:3000/users
从用户登录时需要的 URL 访问。
Main
:
<Switch>
<div className="someclass">
<Header />
<Route exact path='users' component={Users} />
<Footer />
</div>
<Route component={NotFound} /> . ** This also doesn't work here **
</Switch>
解决方案
看看下面的代码来达到你想要的结果:
<Switch>
{this.props.notLoggedIn === true
? <Route path='/' component={LandingPage}/>
: <Dashboard />
}
<Route component={PageNotFound}/>
</Switch>
在上述情况下,我将登录页面显示为默认路由,如果用户登录仪表板,则会显示(包含更多路由)。为了掌握用户是否经过身份验证,我auth
通过登录页面中的提交来设置状态,例如
handleSubmit = (e) => {
e.preventDefault()
const { value} = this.state
const { dispatch } = this.props
dispatch(setAuthedUser(value))
}
在我的应用程序中之后,我可以访问它并设置notLoggedIn
道具。看
function mapStateToProps ({ authedUser }) {
return {
notLoggedIn: authedUser === null
}
}
如果没有匹配的路由,PageNotFound
则显示组件。
有关完整代码,请查看 repo: Repo
推荐阅读
- javascript - 如何将服务响应数据从 fetch API 发送到客户端?
- python - 如何在python中将二进制转换为字符串?
- docker - Could not find a required file
- python - Putting data from .csv files in an array
- c# - 为什么运行游戏时编辑器脚本中的目标为空?
- javascript - TypeError: expressValidator 不是函数版本 6.10.0
- jmeter - 性能测试时一次可以执行多少个线程组?
- javascript - How to make this code of slider work for many sliders on the same page
- javascript - JS 代码无法按预期在 Web 浏览器上运行
- angular - 为什么 Ionic 4 不支持 nativeURL file://