首页 > 解决方案 > 如何当它在其中遇到 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。

标签: reactjsreact-routerreact-router-domdynamic-routing

解决方案


尽管文档建议仅将RouteorRedirect组件作为直接子级,但 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>

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


推荐阅读