[英]issue with react-router showing component when not in route
我正在使用react-router,并且在行为方面遇到一些困难。
Nav
根据需要在所有页面上显示。 但是, Profile
也会显示在所有页面上。 我只想在/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/music
,您将看到其他组合。
希望这可以帮助。 :)
编辑:将 Router
添加到代码中。
编辑:可在此处使用的工作代码: https : //codesandbox.io/s/8x9pql9m19
将右侧的路线更改为:
/home
/home/players
/home/music
/charts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.