繁体   English   中英

错误:useRoutes() 只能在 a 的上下文中使用<router>组件,即使应用程序被 BrowserRouter 包裹</router>

[英]Error: useRoutes() may be used only in the context of a <Router> component even if the app is wrapped around BrowserRouter

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

我在网页中收到一条错误Error: useRoutes() may be used only in the context of a <Router> 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")
);

应用程序.js

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

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

你需要确定你喜欢使用哪个版本,如果是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>

查看这些链接v6 v5

我很确定您不需要将Routes组件包装在 React Fragment 中。 似乎它也可能会导致此处提到的反应路由器出现问题。

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

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

如果您使用react-router-dom版本 6 组件,那么您需要使用react-router-dom -router-dom 版本 6。 您可以删除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

您可以尝试以这种方式包装您的组件

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
  <App />
</BrowserRouter>
</React.StrictMode>
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM