![](/img/trans.png)
[英]Error: useRoutes() may be used only in the context of a <Router> component
[英]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>
我很確定您不需要將Routes
組件包裝在 React Fragment 中。 似乎它也可能會導致此處提到的反應路由器出現問題。
另外我會在gigs
前面添加一個/
,或者將gigs
路由嵌套在/
路由中。
這里的問題是您指定了兩個不同的版本。 您使用的路由器來自 v5,但Routes
和Route
組件需要一個提供特定 v6 上下文的 v6 路由器。
如果您使用react-router-dom
版本 6 組件,那么您需要使用react-router-dom
-router-dom 版本 6。 您可以刪除react-router
,因為react-router-dom
會重新導出這些組件。
從項目目錄運行命令:
卸載react-router
和react-router-dom
npm uninstall -s react-router react-router-dom
安裝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.