gpt4 book ai didi

reactjs - react 路由器中组件的不同导航栏

转载 作者:行者123 更新时间:2023-12-05 05:03:11 27 4
gpt4 key购买 nike

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>
)
}

最佳答案

您可以围绕需要呈现 Navbar 的 Route 编写一个简单的包装器,并为不需要通用 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 如果它们还需要共享 Navbar

关于reactjs - react 路由器中组件的不同导航栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61855638/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com