我创建了一个React应用,该应用最终将根据API调用动态分配路由。现在,我已经对组件进行了硬编码,而我只是试图根据导航选择来切换页面视图以查看每个组件。我将Nav设置为在切换视图之外,以便它始终在页面上呈现,但是当我尝试将WelcomePage设置为本地路线时,它也是唯一在页面上呈现的东西,即使选择其他组件也没有任何改变我的导航页面有什么建议/想法为什么会发生这种情况以及我该如何解决?
下面的代码
Main App Component
import React from 'react'
import { Route, Redirect, Switch } from 'react-router-dom'
import ApplicationPage from './pages/ApplicationPage'
import FrameworkPage from './pages/FrameworkPage'
import WelcomePage from './pages/WelcomePage'
import Nav from './components/Nav'
const App = () => (
<>
<Route path={['/app/:appId', '/']} component={Nav} />
<Switch>
<Route path={['/app/:appId', '/']} component={WelcomePage} />
<Route path={['/app', '/Framework']} component={FrameworkPage} />
<Route
path={['/app/:appId/setting/:settingKey', '/app/:appId', '/app']}
component={ApplicationPage}
/>
<Redirect to="/app/foo" />
</Switch>
</>
)
export default App
Nav Component
import React from 'react'
import styled from 'styled-components'
import { useAppState } from '../store'
const Nav = ({ match, history }) => {
const [appState] = useAppState()
return (
<StyledNav>
<h1>Title of Page</h1>
<select
defaultValue={match.params.appId}
onChange={({ target }) => history.replace(`/app/${target.value}`)}
>
<option>Choose App</option>
{appState.apps.map(opt => (
<option key={opt}>{opt}</option>
))}
</select>
</StyledNav>
)
}
const StyledNav = styled.nav`
padding: 20px 10px;
background: black;
color: white;
h1 {
margin: 0;
}
`
export default React.memo(
Nav,
(prevProps, nextProps) =>
prevProps.match.params.appId === nextProps.match.params.appId
)
答案 0 :(得分:1)
所以我认为正在发生的事情是,因为您在Switch外部定义了Nav路线并为其提供了路径。它总是最终会呈现在其他所有东西之上,因为您将路径作为要求,并且无论何时导航到其他地方,仍然满足该路径。您可以做的就是将导航的所有路线全部移除,然后执行此操作。这将使Nav无论在什么情况下都显示在顶部,而不会中断您的导航。您似乎还没有导入BrowserRouter。
import React from 'react'
import { BrowserRouter, Route, Redirect, Switch } from 'react-router-dom'
import ApplicationPage from './pages/ApplicationPage'
import FrameworkPage from './pages/FrameworkPage'
import WelcomePage from './pages/WelcomePage'
import Nav from './components/Nav'
const App = () => (
<BrowserRouter>
<div>
<Nav/>
<Switch>
<Route path={['/app/:appId', '/']} component={WelcomePage} />
<Route path={['/app', '/Framework']} component={FrameworkPage} />
<Route
path={['/app/:appId/setting/:settingKey', '/app/:appId', '/app']}
component={ApplicationPage}
/>
<Redirect to="/app/foo" />
</Switch>
</div>
<BrowserRouter/>
)
export default App