The Problem:

我们有一个应用程序,它定义了它自己的路由和组件(例如Home、About Us等),但也消费了一个名为Basket的内部NPM包.

问题是篮子组件有多个steps(例如,用户详细信息、支付等),我们计划使用Reaction路由V6来处理每个步骤之间的导航.

在阅读了文档并浏览了Stack之后,标准方法是:

<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/basket">
      <Route path="/user-details" element={<PaymentDetails />} />
    </Route>
  </Routes>
</BrowserRouter>

问题是我们不能这样定义它,因为篮子要在多个应用程序中使用,维护它应该像做npm install package@latest个一样简单.

Questions:

由于以下内容不起作用并导致此错误,我们如何实现这一点?

[Basket] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
    <Basket countryCode="GB" />    
  </Routes>
</BrowserRouter>
export const Basket = ({
  countryCode,
}: BasketProps) => (
  // Attempted the following line as a Route and Fragment with both resulting in the attached error
  <Route path="/basket">
    <Route
      path="/mobile-capture"
      element={<UserDetails countryCode={countryCode} />}
    />
    // ... All other components
  </Route>
);

Sidenote:

我能做到这一点的唯一方法是使用下面的方法,但由于几个原因(即使用多个<Routes />在任何地方都没有文档记录),它感觉不正确.

<BrowserRouter>
  <Routes>
    <Route path="/" element={<Home />} />
  </Routes>
  <Routes>
    <Basket countryCode="GB" />    
  </Routes>
</BrowserRouter>
export const Basket = ({
  countryCode,
}: BasketProps) => (
  <Routes>
    <Route
      path="/user-details-capture"
      element={<UserDetails countryCode={countryCode} />}
    />
    // ... All other components
  </Routes>
);

推荐答案

使用多个Routes不是问题.您在两个位置(您的篮子文件和路由文件)中都有<Routes>.如果可能的话,我也会建议使用元素.

    <Routes>
      <Route path="/basket/*" element={<Basket />} />
      <Route path="/bucket/*" element={<Bucket />} />
    </Routes>

在您的BasketBucket组件中,您可以:

const Basket = () => {
  return (
    <Routes>
      <Route path="/mobile-capture" element={<X />} />
      <Route path="/mobile-capture2" element={<Y />} />
    </Routes>
  );
};

文档和讨论表明Routes很酷: https://reactrouter.com/en/main/upgrading/v5#upgrade-all-switch-elements-to-routeshttps://github.com/remix-run/react-router/discussions/9841

<Routes>似乎只是为匹配子路由提供了一个背景.

Typescript相关问答推荐

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

在将对象从一个对象转换成另一个对象时,可以缩小对象的键吗?

`((PrevState:NULL)=>;NULL)|null`是什么意思?

基于键的值的打字动态类型;种类;

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

带switch 的函数的返回类型的类型缩小

在包含泛型的类型脚本中引用递归类型A<;-&B

如何解决类型T不能用于索引类型{ A:typeof A; B:typeof B;. }'

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

有没有可能产生输出T,它在视觉上省略了T中的一些键?

如何在React组件中指定forwardRef是可选的?

有没有办法取消分发元组的联合?

基于泛型的条件接口键

自定义 Select 组件的类型问题:使用带逗号的泛型类型<;T与不带逗号的<;T&>;时出错

为什么TypeScrip不能解析对象析构中的赋值?

使用强类型元组实现[Symbol.iterator]的类型脚本?

如何通过转换器类继承使用多态将对象从一种类型转换为另一种类型

如何使用angular15取消选中位于其他组件中的复选框

如何让Record中的每个值都有独立的类型?

广义泛型类型不加载抽象类型上下文