反应路由器中组件的不同导航栏

时间:2020-05-17 17:06:22

标签: reactjs react-router

m试图为其中一个组件构建一个单独的导航栏。 我试图将其移至Switch元素之外,但效果不佳。 有什么建议吗?

这是代码:

import React, { useEffect } from 'react'
import { Switch, Route } from 'react-router-dom'

const App = () => {
return (
    <Provider store={store}>
      <NavBar />
      <Switch>
        <Route exact path='/' component={Home} />
        <Route exact path='/about' component={About} />
        <Route exact path='/landingPageExample' component={LandingExample} />

        <Route exact path='/landingPage/:username' component={Landing}/> // That the component I'm
        trying to have for a different Navbar

        <AuthRoute exact path='/login' component={Login} />
        <AuthRoute exact path='/signup' component={Signup} />
        <ProtectedRoute exact path='/editLandingPage' component={EditLandingPage} />
        <ProtectedRoute exact path='/editUser' component={EditUser} />
        <ProtectedRoute exact path='/editPost' component={EditPost} />
        <ProtectedRoute exact path='/collectedEmails' component={Sheets} />
        <Route component={NotFound} />
      </Switch>
    </Provider>
  )
}

1 个答案:

答案 0 :(得分:1)

您可以围绕Route编写一个简单的包装,该包装需要渲染Navbar,并为不需要通用Navbar的组件使用常规Route

import React, { useEffect } from 'react'
import { Switch, Route } from 'react-router-dom'


const RouteWithNavbar = ({exact, path, component:Component, ...rest}) => {
   return <Route exact={exact} path={path} {...rest} render={(routeProps) => {
      return <><Navbar {...routeProps}/><Component {...routeProps}/>
   }}
   />
}
const App = () => {
return (
    <Provider store={store}>
      <Switch>
        <RouteWithNavbar exact path='/' component={Home} />
        <RouteWithNavbar exact path='/about' component={About} />
        <RouteWithNavbar exact path='/landingPageExample' component={LandingExample} />

        <Route exact path='/landingPage/:username' component={Landing}/> 

        <AuthRoute exact path='/login' component={Login} />
        <AuthRoute exact path='/signup' component={Signup} />
        <ProtectedRoute exact path='/editLandingPage' component={EditLandingPage} />
        <ProtectedRoute exact path='/editUser' component={EditUser} />
        <ProtectedRoute exact path='/editPost' component={EditPost} />
        <ProtectedRoute exact path='/collectedEmails' component={Sheets} />
        <RouteWithNavbar component={NotFound} />
      </Switch>
    </Provider>
  )
}

还请注意,如果AuthRouteProtectedRoute也需要共享导航栏,则会在内部使用RouteWithNavbar