【问题标题】:Error: useRoutes() may be used only in the context of a <Router> component even if the app is wrapped around BrowserRouter错误:useRoutes() 只能在 <Router> 组件的上下文中使用,即使应用程序包裹在 BrowserRouter 周围
【发布时间】:2022-01-22 04:37:47
【问题描述】:

我需要在 2 条路径之间进行路由, 我安装了npm install react-router (react-router: 6.2.1 and react-router-dom: 5.2.0)。

我在网页 Error: useRoutes() may be used only in the context of a &lt;Router&gt; component. 中收到一条错误消息,这最终意味着我没有使用 BrowserRouter 扭曲我的 index.js 文件,但我做到了。

代码: index.js

import {BrowserRouter as Router}  from "react-router-dom";

ReactDOM.render(
  <React.StrictMode>
  <Router>
    <App />
    </Router>
  </React.StrictMode>,
  document.getElementById("root")
);

app.js

function App() {
  return (
  <>
    <Routes>
    <Route path ="/" element={<Main />} />
    <Route path ="gigs" element={<Gigs />} />
    </Routes>
</>
  );
}

【问题讨论】:

  • 我无法重现您的问题,所以我猜错误出在其他地方。您能否提供一个可重现的示例?

标签: reactjs react-router react-router-dom


【解决方案1】:

这里的问题是反应路由器版本和您使用的目标版本之间的错误......

你需要确定你喜欢使用哪个版本,如果是v6,那么你需要遵循v6规则,如果是v5那么你需要遵循v5...

例如:

"react-router": "6.2.1",
"react-router-dom": "6.2.1"

现在查看代码差异: 在 V6 中:

  <Routes>
    <Route path="/" element={<Layout />}>
      <Route index element={<Home />} />
      <Route path="about" element={<About />} />
      <Route path="dashboard" element={<Dashboard />} />

      {/* Using path="*"" means "match anything", so this route
            acts like a catch-all for URLs that we don't have explicit
            routes for. */}
      <Route path="*" element={<NoMatch />} />
    </Route>
  </Routes>

在 V5 中:

    <Router>
<Switch>
      <Route exact path="/">
        <Home />
      </Route>
      <Route path="/about">
        <About />
      </Route>
      <Route path="/dashboard">
        <Dashboard />
      </Route>
    </Switch>
  </div>
</Router>

查看这些链接v6v5

【讨论】:

    【解决方案2】:

    这里的问题是您指定了两个不同的版本。您使用的路由器来自 v5,但 RoutesRoute 组件需要一个提供特定 v6 上下文的 v6 路由器。

    如果您使用的是 react-router-dom 版本 6 组件,那么您需要使用版本 6 的 react-router-dom。您可以删除 react-router,因为 react-router-dom 会重新导出这些组件。

    从项目目录运行命令:

    1. 卸载react-routerreact-router-dom

      npm uninstall -s react-router react-router-dom

    2. 安装react-router-dom 版本 6

      npm install -s react-router-dom

    【讨论】:

      【解决方案3】:

      我很确定您不需要将 Routes 组件包装在 React 片段中。它似乎也可能导致反应路由器as mentionned here出现问题。

      另外我会在gigs 前面添加一个/,或者将gigs 路由嵌套在/ 路由中。

      【讨论】:

        猜你喜欢
        • 2021-01-31
        • 2021-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-29
        • 2022-11-15
        相关资源
        最近更新 更多