[英]react router not rendering components at route
My root component is shown below:我的根组件如下所示:
ReactDOM.render(
<Provider store={store}>
<Router>
<Menu />
<Switch>
<Route path='/'>
<Home />
</Route>
<Route path='/about'>
<About />
</Route>
</Switch>
</Router>
</Provider>,
document.getElementById('root')
)
and then my Menu component is shown below:然后我的菜单组件如下所示:
function Menu() {
return (
<ul className='menu'>
<li className='menu-item'>
<Link to='/'>Home</Link>
</li>
<li className='menu-item'>
<Link to='/about'>About</Link>
</li>
</ul>
)
}
export default withRouter(Menu)
The problem is that when I click the relevant link, my About
component does not render but the url shows up in the url bar.问题是,当我单击相关链接时,我的
About
组件没有呈现,但 url 显示在 url 栏中。 I am not sure what's wrong and I have gone through all of the questions related to this topic and none of their suggestions have helped me.我不确定出了什么问题,我已经完成了与该主题相关的所有问题,但他们的建议都没有帮助我。 I am using
redux
but I do not think that is what is causing the problem.我正在使用
redux
但我认为这不是导致问题的原因。 Please help!请帮忙!
As mentioned, the exact
prop should be added to the route that renders the Home
component:如前所述,应该将
exact
prop 添加到呈现Home
组件的路由中:
<Router>
...
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
...
</Router>
The reason for that is to restrict rendering of the Home
component to an exact match of "/"
.这样做的原因是将
Home
组件的呈现限制为与"/"
完全匹配。 Without the exact
prop, the Home
component will also be rendered for other partially matched routes (ie "/about"
, which would be considered a partial match).如果没有
exact
道具, Home
组件也将针对其他部分匹配的路由(即"/about"
,这将被视为部分匹配)进行渲染。
Some other suggestions;其他一些建议; you might consider assigning the component rendered for a route via the
component
prop on the Route
component by doing this:您可以考虑通过执行以下操作,通过
Route
组件上的component
prop 分配为路由呈现的component
:
<Route exact path="/" component={Home} />
Additionally, you can avoid wrapping the Menu
component with the withRouter
.此外,您可以避免使用
withRouter
包装Menu
组件。
For a working example, see this link - hope these pointers help!有关工作示例,请参阅此链接- 希望这些指针有所帮助! :)
:)
add exact
to your rout, like this添加
exact
到你的溃败,像这样
<Route exact path='/'>
<Home />
</Route>
<Route exact path='/about'>
<About />
</Route>
Use the Router
logic like this.像这样使用
Router
逻辑。
<Provider store={store}>
<Router>
<Menu />
<Switch>
<Route path='/' exact component = {Home}/>
<Route path='/about' exact component = {About}/>
</Switch>
</Router>
</Provider>,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.