首页 > 解决方案 > 带有 react-router-config 的子路由

问题描述

我正在研究带有子路由的 React SSR,但所有子路由都在一个页面中呈现。

例如:

export const routes = [
  // Some sibling routes go here and since this is nested with <Switch>, those are working fine.
  {
    path: '/user/:id',
    component: Userpage,
    routes: [
      {
        path: '/user/:id/profile',
        component: Profilepage,
      },
      {
        path: '/user/:id/posts',
        component: Postspage,
        routes: [
          {
            path: '/user/:id/posts/:id',
            component: Postpage,
            routes: [
              {
                path: '/user/:id/posts/:id/edit',
                component: Posteditpage,
              },
            ],
          },
        ],
      },
    ],
  },
  {
    component: Notfoundpage,
  },
];
const App = () => {
  return (
    <Switch>
      { renderRoutes(routes, initialData) }
    </Switch>
  );
};

使用此模式打印页面:

import React from 'react';
import { renderRoutes } from 'react-router-config';

const Userpage = ({ route }) => {
  const { routes } = route;
  return (
    <div>
      <h1>
        This is the user page
      </h1>
      { renderRoutes(routes) }
    </div>
  );
};

export default Userpage;

在这条路线上呈现这个,http://localhost:3000/user/me/posts/firstpost/edit


这是用户页面

这是帖子页面

在此处显示所有帖子

这是帖子

此处仅显示一篇文章

这是postitit页面

在这里编辑帖子


我如何使它呈现单独的页面,我需要将所有路由设置为兄弟姐妹吗?不过这似乎不对。

标签: routesreact-routerserver-side-rendering

解决方案


如果您不想将父路由布局与子路由一起显示,则应将子路由与父路由放在同一级别。演示子路由行为的片段 https://stackblitz.com/edit/react-router-config

const routes = [
  {
    component: Root,
    routes: [
      {
        path: '/',
        exact: true,
        component: Home
      },
      { // moved it from 'Child.routes' to the root level
        path: '/child/:id/grand-child',
        component: GrandChild
      },
      {
        path: '/child/:id',
        component: Child,
      }
    ]
  }
]

推荐阅读