在Reaction-Router-DOM6中,我使用的是useRoutes,因此我构建了一个路由对象.我有一条路由,我希望路由的顶部有一个布局,然后根据参数不同的网点.

因此,例如:

/wizard/step1 -> Step1Page
/wizard/step2 -> Step2Page

我建造这个的方式,看起来是这样的:

const routes = [
  {
    path: '/wizard/:step',
    element: <WizardLayout />, // this has an <Outlet />
    children: [
      {
        path: '/wizard/step1',
        element: <Step1Page />,
      },
      {
        path: '/wizard/step2',
        element: <Step2Page />,
      },
    ],
  },
];

这会抛出一个错误,即子路径"必须以其父路径的完整路径开始".这意味着布局应具有如下路径:

{
  path: '/wizard',
  element: <WizardLayout />,
  children: [ ... ],
}

但是,这样做会导致子元素在调用useParams时无法识别:step参数,因为它实际上并未在路径中定义.

重申一下,我希望布局应用于类型为/wizard/:step的所有路由,并在特定的:step参数中包含特定的元素.我该怎么做?

推荐答案

如错误所示,您不能将绝对路径"/wizard/step1"嵌套在绝对路径"/wizard/:step"下.为了使动态路径段stepWizardLayout可用,那么您有几个选项.

  1. 将子路由移到WizardLayout中的switch语句中,以取代Outlet.

    const router = createBrowserRouter([
      ...
      {
        path: '/wizard/:step',
        element: <WizardLayout />,
      },
      ...
    ]);
    
    const WizardLayout = () => {
      const { step } = useParams();
    
      const getStep = () => {
        switch(step) {
          case "step1":
            return <Step1Page />;
    
          case "step2":
            return <Step2Page />;
    
          default:
            return null;
        }
      }
    
      return (
        <>
          ... Wizard Layout UI ...
          {getStep()}
          ...
        </>
      )
    };
    

    Edit wizardly-easley-thq4df

  2. 更新路由声明,以便嵌套路由可以工作,并使用WizardLayout中的useMatch钩子来匹配"/wizard/:step"路径.

    const router = createBrowserRouter([
      ...
      {
        path: '/wizard',
        element: <WizardLayout />,
        children: [
          {
            path: 'step1',
            element: <Step1Page />,
          },
          {
            path: 'step2',
            element: <Step2Page />,
          },
        ],
      },
      ...
    ]);
    
    import { Outlet, useMatch } from 'react-router-dom';
    
    const WizardLayout = () => {
      const match = useMatch('/wizard/:step');
      const { step } = match?.params;
    
      return (
        <>
          ... Wizard Layout UI ...
          <Outlet />
          ...
        </>
      )
    };
    

    Edit react-router-6-how-to-define-child-routes-for-specific-params (v2)

Typescript相关问答推荐

Typescript对每个属性具有约束的通用类型

有没有办法适当缩小类型?

为什么缩小封闭内部不适用于属性对象,但适用于声明的变量?

更新为Angular 17后的可选链运算符&?&问题

为什么我的Set-Cookie在我执行下一次请求后被擦除

我可以以这样一种方式键入对象,只允许它的键作为它的值吗?

路由链接始终返回到

如何从扩展接口推断泛型?

使用2个派生类作为WeakMap的键

从泛型类型引用推断的文本类型

编译TypeScrip项目的一部分导致错误

在React中定义props 的不同方式.FunctionalComponent

类型与泛型抽象类中的类型不可比较

使用或属性编写无限嵌套的接口

基于属性值的条件类型

Select 类型的子项

如何为对象数组中的每个条目推断不同的泛型

React Context TypeScript错误:属性';firstName';在类型';iCards|iSearch';

两个接口的TypeScript并集,其中一个是可选的

使用嵌套属性和动态执行时,Typescript 给出交集而不是并集