嵌套路由不使用 React Router v4 渲染 [英] Nested Routes not rendering with React Router v4
问题描述
我正在尝试将我的一些路由与 React Router v4 组合在一起以清理我的一些组件.现在,我只想将未登录的路由组合在一起,并将管理路由组合在一起,但以下方法不起作用.
I am trying to group some of my routes together with React Router v4 to clean up some of my components. For now I just want to have my non logged in routes group together and my admin routes grouped together but the following doens't work.
const Main = () => {
return (
<main>
<Switch>
<Route exact path='/' component={Public} />
<Route path='/admin' component={Admin} />
</Switch>
</main>
);
};
export default Main;
public.js
const Public = () => {
return (
<Switch>
<Route exact path='/' component={Greeting} />
<Route path='/signup' component={SignupPage} />
<Route path='/login' component={LoginPage} />
</Switch>
);
};
export default Public;
Greeting 组件显示在localhost:3000/",但 SignupPage 组件不显示在localhost:3000/signup"并且登录组件不显示在localhost:3000/signup".查看 React Dev Tools 这两条路由返回 Null.
The Greeting component shows at "localhost:3000/", but the SignupPage component does not show at "localhost:3000/signup" and the Login component doesn't show at "localhost:3000/signup". Looking at the React Dev Tools these two routes return Null.
推荐答案
原因很明显.对于 main.js 中的路由,您已使用精确的 exact path='/'
指定了 Public
组件的路由路径,然后在 Public 组件中匹配其他路线
.因此,如果路由路径是 /signup
,则起初路径并不准确,因此不会呈现 Public
组件,因此不会呈现子路由.
The reason is very obvious. for your route in main.js, you have specified the Route path of Public
component with exact exact path='/'
and then in the Public component you are matching for the other Routes
. So if the route path is /signup
, at first the path is not exact so Public
component is not rendered and hence no subRoutes will.
将您的路由配置更改为以下内容
Change your route configuration to the following
main.js
const Main = () => {
return (
<main>
<Switch>
<Route path='/' component={Public} />
<Route path='/admin' component={Admin} />
</Switch>
</main>
);
};
export default Main
public.js
const Public = () => {
return (
<Switch>
<Route exact path='/' component={Greeting} />
<Route path='/signup' component={SignupPage} />
<Route path='/login' component={LoginPage} />
</Switch>
);
};
此外,当您指定嵌套路由时,这些应该是相对于父路由的,例如,如果父路由是 /home
然后在子路由中您希望编写 /仪表板
.应该这样写
Also when you are specifying the nested routes these should be relative to the parent Route, for instance if the parent route is /home
and then in the child Route you wish to write /dashboard
. It should be written like
<Route path="/home/dashboard" component={Dashboard}
甚至更好
<Route path={`${this.props.match.path}/dashboard`} component={Dashboard}
这篇关于嵌套路由不使用 React Router v4 渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!