reactjs - 如何当它在其中遇到 React 组件时工作?
问题描述
基本上我正在理解别人的代码并进行修改。在 App.js 中检查用户是否登录,他必须呈现仪表板
应用程序.js
<Switch>
<Redirect exact path="/" to="/dashboard"/>
<Route path="/login" component={GuestBoard} />
<EnsureSignedIn>
<Switch>
<Route path="/dashboard/" component={Dashboard}/>
<Route path="/welcome/" component={Welcome}/>
</Switch>
</EnsureSignedIn>
</Switch>
基本上<EnsureSignedIn>
检查用户是否已登录,它会呈现所有孩子。
我的问题是:没有路径的渲染如何。<Switch>
<EnsureSignedIn>
如果我继续在里面写 React 组件,到底会发生什么(组件的渲染流程是什么)<Switch>
?
说这样的话
<Switch>
<Redirect exact path="/" to="/dashboard"/>
<Route path="/login" component={GuestBoard} />
<Component1 />
<Component2 />
<Component3 />
</Switch>
确保登录:
componentDidMount() {
if (!this.props.user) {
this.props.history.push('/login?next=' + this.props.currentURL);
}
render() {
return (this.props.user ? this.props.children : null);
}
我们使用了 redux,所以 user 是 reducer 的 props。
解决方案
尽管文档建议仅将Route
orRedirect
组件作为直接子级,但 Switch 在此处按预期工作。然而,据记载,Switch 将呈现单个子节点——与当前路由匹配的第一个子节点。它还指定<Route
允许没有路径的组件作为包罗万象,这就是这里发生的事情。
为简化起见,Switch 将从上到下一个接一个地遍历其所有子组件,并选择路径与当前路由匹配的第一个组件,或者该组件没有指定路径(catch-all 组件)。你可以在这里看到这个工作:https ://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Switch.js#L47请注意,它正在寻找Route
组件的道具,但那里没有代码特别要求组件是Route
.
在您的情况下,未经身份验证的页面将呈现得很好,因为它们出现在子EnsureSignIn
组件之前。但是,如果没有其他路由匹配,EnsureSignIn
则将呈现,并且如果用户未登录,该组件可能会重定向回登录页面 - 阻止他们访问下面的受保护页面。
如果您要像这样重组代码:
<Switch>
<span>Hello!!</span>
<Redirect exact path="/" to="/dashboard"/>
<Route path="/login" component={GuestBoard} />
<EnsureSignedIn>
<Switch>
<Route path="/dashboard/" component={Dashboard}/>
<Route path="/welcome/" component={Welcome}/>
</Switch>
</EnsureSignedIn>
</Switch>
这也是完全有效的,但唯一会被渲染的是“你好!!” 因为这是第一个匹配的组件。
推荐阅读
- sql-server - 使用 Node.JS 和 SQL Server Always Encrypted 插入数据库时出错
- angular - ng-bootstrap 的 ngbDatepicker 不起作用
- javascript - 编写单个 JS 脚本以将 ID 分配给 HTML 中的输出
- android - 无导航编辑器 - Android Studio Canary 15 和 16
- ruby-on-rails - Ruby on Rails - 为帖子添加评论
- swing - 在 JavaFX 中设置本机分辨率
- opengl - glDrawElements 不呈现来自 obj 文件的输入
- symfony - knpMenuBundle symfony 4
- ios - iOS - 在设备上安装未签名的 .ipa
- javascript - 反应路由器错误:您不应该在路由器之外使用路由