【问题标题】:How <Switch> works when it encounters React Components in it?<Switch> 在遇到 React 组件时如何工作?
【发布时间】:2018-05-31 11:03:30
【问题描述】:

基本上我是在理解别人的代码并进行修改。在 App.js 中检查用户是否登录,他必须呈现仪表板

App.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>

基本上&lt;EnsureSignedIn&gt;会检查用户是否登录,它会渲染所有的孩子。

我的问题是:&lt;Switch&gt; 如何渲染没有路径的&lt;EnsureSignedIn&gt; 还有究竟发生了什么(渲染组件的流程是什么)如果我继续在 &lt;Switch&gt; 中编写 React 组件?

这样说

       <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 或 Redirect 元素。 github.com/ReactTraining/react-router/blob/master/packages/…
  • 是的。有用 !!!连我都感到惊讶。
  • 如果这不是正确的实施方式,请告诉我。
  • 好吧,如果它有效,那么我认为没关系。你能粘贴EnsureSignedIn 的代码吗?
  • EnsureSignedIn: 没有什么内容

标签: reactjs react-router react-router-dom dynamic-routing


【解决方案1】:

尽管文档建议仅将 RouteRedirect 组件作为直接子组件,但 Switch 在此处按预期工作。然而,据记载,Switch 将渲染一个子节点——与当前路由匹配的第一个子节点。它还指定允许将没有路径的&lt;Route 组件作为包罗万象,这就是这里发生的事情。

为简化起见,Switch 会从上到下逐个遍历其所有子节点,并选择路径与当前路由匹配的第一个组件该组件没有指定路径(包罗万象的组件)。你可以在这里看到这个工作: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>

这也是完全有效的,但唯一会被渲染的是“你好!!”因为这是第一个匹配的组件。

【讨论】:

  • 很好的答案!谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-12-02
  • 2022-11-24
  • 2018-03-17
  • 2016-09-11
  • 2021-12-25
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
相关资源
最近更新 更多