我正在使用react-router,但它的行为有一些困难。
Nav
根据需要显示在所有页面上。但是,个人资料
也会显示在所有页面上。我只想在 /home
以及 /music
和 /players
页面上显示它,它确实如此。但是,它也显示在 /charts
页面上,这让我感到困惑。
我的代码如下所示。
import React from 'react';
import { Route } from 'react-router-dom'
import Nav from './components/Nav'
import Profile from './components/Profile'
import Players from './components/Players'
import Music from './components/Music'
import Charts from './components/Charts'
const App = () => {
return (
<section>
<Nav />
<Route path="/home">
<div>
<Profile avatarUrl={ avatarUrl }/>
<Route path="/players" component={Players}/>
<Route path="/music" component={Music}/>
</div>
</Route>
<Route path="/charts" component={Charts}/>
</section>
)
}
export default App;
我已通读文档,尝试放入 Switch
组件,将 exact
添加到 home
路由,但这会导致其他意外情况行为。
谁能告诉我我做错了什么?
谢谢皮特!
最佳答案
试试这个:
import React from 'react';
import { Route, BrowserRouter as Router } from 'react-router-dom'
import Nav from './components/Nav'
import Profile from './components/Profile'
import Players from './components/Players'
import Music from './components/Music'
import Charts from './components/Charts'
const Home = ({match}) => {
return (
<div>
<Profile avatarUrl={ avatarUrl }/>
<Route path=`${match.url}/players` component={Players}/>
<Route path=`${match.url}/music` component={Music}/>
</div>
);
};
const App = () => {
return (
<section>
<Nav />
<Router>
<Switch>
<Route path="/charts" exact={true} component={Charts}/>
<Route path="/home" component={Home} />
</Switch>
</Router>
</section>
)
}
export default App;
我还没有测试过这个,但这应该有效。
假设你正在使用react-router v4,我不知道你是否真的可以按照你使用的方式使用你的家庭路由。
在上面的代码中,Switch 基本上渲染了其下指定的路由之间的第一个匹配项。确切的关键字将确保只有 /charts
路径会显示 Charts
组件。
Home
组件将在以 /home
开头的任何路径中呈现。
现在,对于路径 /home/players
,您将看到 Profile
和 Players
组件,而对于路径 /home/音乐
,您会看到其他组合。
希望这有帮助。 :)
编辑:
将 Router
添加到代码中。
编辑:
此处提供工作代码:https://codesandbox.io/s/8x9pql9m19
将右侧路线更改为:
/home
/home/players
/home/music
/图表
关于javascript - react 路由器在不在 route 时显示组件的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49209092/