我正在设置一个基本的导航栏,它只有一些按钮,没有任何复杂的日志或任何东西。当我在 switch 内部有这个导航栏时,没有其他组件加载,这意味着我无法将导航栏包装在某些组件之间,当我在 switch 外部有导航栏时,它就可以工作,我可以检查是否 props.match.location等是“/”并且不在主页上加载它,所以我找到了一个解决方法,但是可能导致这个错误的原因是什么,或者它是预期的行为,我怀疑我的野路线,但不是100%确定什么。 我在哪里使用导航栏
const App = () => {
return (
<div>
<Router>
<Switch>
<Route component={theNavbar} />
<Route exact path="/" component={Home} />
<Route exact path="/api/:city/electronics" component={Electronics} />
<Route exact path="/api/:city/labour" component={Labour} />
<Route exact path="/api/posts/item/:id" component={ItemDetails} />
<Route exact path="/create/:city/:category" component={CreatePost} />
</Switch>
</Router>
</div>
);
};
最佳答案
这完全是预期的行为,并且由几个因素引起。首先是Switch
,第二个是匹配任何内容 Route
对于导航。
<强> Switch
Renders the first child
<Route>
or<Redirect>
that matches the location.
所有后续匹配都不会呈现。
<强> Route path
Routes without a path always match.
<Route component={theNavbar} />
该路线匹配所有位置,因此将始终匹配。在 Switch
中首先列出意味着它将始终呈现。
始终渲染某些导航组件同时仍匹配其他路线的解决方案是将该组件移至 Switch
之外但仍在 Router
之内.
关于javascript - 导航栏导致其他组件无法在 React Router 中加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60688849/