【问题标题】:React router rendering multiple componentsReact 路由器渲染多个组件
【发布时间】:2021-09-12 07:54:16
【问题描述】:

在我的 react 应用程序中,我使用 react router 进行路由,而在我的应用程序中,我不想为 login page, create account page, etc. 等某些路由呈现导航栏。此外,当用户输入一个不存在的路由时,它应该呈现一个 404 页面。

我该怎么做?为了呈现这样的页面,我必须做什么样的安排。在当前设置下,它正在渲染 404 页面以及 login and register pages

我该如何解决这个问题?

 {/* Routes Without Nav */}
      <Switch>
        <Route exact path="/login">
          <Login notify={setResMessage} />
        </Route>
        <Route exact path="/user/create">
          <CreateAc notify={setResMessage} />
        </Route>
        <Route exact path="/mobile/search">
          <MobileSearchPage notify={setResMessage} />
        </Route>
        <Navbar notify={setResMessage} />
      </Switch>

      <Switch>
        {/* Routes With Nav */}
        <Route exact path="/">
          <Home notify={setResMessage} />
          <Footer />
        </Route>
        <Route exact path="/cart">
          <Cart />
        </Route>
        <Route exact path="/product/:productID">
          <ProductDetails notify={setResMessage} />
        </Route>
        <Route exact path="/search/:product">
          <SearchPage notify={setResMessage} />
        </Route>
        <Route exact path="/payment-success">
          <PaymentSuccess />
        </Route>
        <Route exact path="/recommended">
          <Recommendations />
        </Route>
        {/* ----------------Not So IMP Routes---------------- */}
        <Route exact path="/create-product" component={AddProduct} />
        <Route component={PageNotFound} />
      </Switch>

【问题讨论】:

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


    【解决方案1】:

    对于导航栏,您可以设置一个条件来阻止它在组件本身中显示:

    类似这样的:

    function Nav() {
      const location = useLocation();
      if (location.pathname !== "/page2") return <h3>NAV BAR</h3>;
      return null;
    }
    

    而对于404页面,你把它放在Switch的最后,如果没有匹配到的路由,则渲染404:

    <Switch>
      <Route exact path="/">
        <Home />
      </Route>
      <Route path="/page1">
        <Page1 />
      </Route>
      <Route path="/page2">
        <Page2 />
      </Route>
      <Route path="*">
        <Page404 />
      </Route>
    </Switch>;
    

    现场示例:

    【讨论】:

      【解决方案2】:

      最好的做法是制作一个 Layout 组件,并在您想在 layout 周围显示导航栏和其他相关内容时使用它。应该是这样的

      function Layout(props) {
        const { children } = props ;  
        return (
          <div> 
            <Navbar/> 
             {children}
          </div>
        ) 
      }
      
      function ComponentsWithLayout() { 
        return ( 
          <Layout> 
            {/* component code comes here */}
         </Layout> 
        ) 
      }

      【讨论】:

        猜你喜欢
        • 2018-10-18
        • 2018-01-14
        • 1970-01-01
        • 1970-01-01
        • 2019-06-21
        • 1970-01-01
        相关资源
        最近更新 更多