简体   繁体   English

React Router V6 - 错误:useRoutes() 只能在 a 的上下文中使用<router>成分</router>

[英]React Router V6 - Error: useRoutes() may be used only in the context of a <Router> component

I have installed react-router-dom V6-beta.我已经安装了react-router-dom V6-beta。 By following the example from a website I am able to use the new option useRoutes I have setup page routes and returning them in the App.js file.通过遵循网站上的示例,我可以使用新选项useRoutes我已经设置了页面路由并将它们返回到App.js文件中。

After saving I am getting the following error:保存后出现以下错误:

Error: useRoutes() may be used only in the context of a component.错误:useRoutes() 只能在组件的上下文中使用。

I am wondering If I am missing something here?我想知道我是否在这里遗漏了什么? I have created the pages inside the src/pages folder.我在src/pages文件夹中创建了页面。

My code:我的代码:

import { BrowserRouter, Link, Outlet, useRoutes } from 'react-router-dom';

// Pages
import Home from './pages/Home';
import About from './pages/About';
import Services from './pages/Services';
import Gallery from './pages/Gallery';
import Prices from './pages/Prices';
import Contact from './pages/Contact';

const App = () => {
    const routes = useRoutes([
        { path: '/', element: <Home /> },
        { path: 'o-nama', element: <About /> },
        { path: 'usluge', element: <Services /> },
        { path: 'galerija', element: <Gallery /> },
        { path: 'cjenovnik', element: <Prices /> },
        { path: 'kontakt', element: <Contact /> }
    ]);

    return routes;
};

export default App;

It think the problem is that you still need to wrap routes ( Routes / useRoutes ) inside a Router element.它认为问题在于您仍然需要将routesRoutes / useRoutes )包装在Router元素中。

So an example looks something like this:所以一个例子看起来像这样:

import React from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  useRoutes,
} from "react-router-dom";

const Component1 = () => {
  return <h1>Component 1</h1>;
};

const Component2 = () => {
  return <h1>Component 2</h1>;
};

const App = () => {
  let routes = useRoutes([
    { path: "/", element: <Component1 /> },
    { path: "component2", element: <Component2 /> },
    // ...
  ]);
  return routes;
};

const AppWrapper = () => {
  return (
    <Router>
      <App />
    </Router>
  );
};

export default AppWrapper;

Refactor according to your needs.根据您的需要进行重构。

You should have a <BrowserRouter> (or any ofthe provided routers ) higher up in the tree.您应该在树的较高位置有一个<BrowserRouter> (或任何提供的路由器)。 The reason for this is that the <BrowserRouter> provides a history context which is needed at the time the routes are created using useRoutes() .这样做的原因是<BrowserRouter>提供了使用useRoutes()创建路由时需要的历史上下文。 Note that higher up means that it can't be in the <App> itself, but at least in the component that renders it.请注意,更高层意味着它不能在<App>本身中,但至少在呈现它的组件中。

Here's what your entry point could look like:这是您的入口点的样子:

import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';


ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root'),
);

Mention below code in index.js在 index.js 中提及以下代码

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

its means in Your index js Or App JS wrap with BrowserRouter like this它在你的 index js 或 App JS 中的意思是这样用 BrowserRouter 包装

import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(
    <React.StrictMode>
        <Provider store={store}>
            <BrowserRouter>  // Like This here I am using
                <App />
           </BrowserRouter>
       </Provider>
    </React.StrictMode>,
    document.getElementById("root"),
);

Code: 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应用程序.js

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

If you want to keep everything in your App-component如果您想将所有内容都保留在您的 App 组件中

import { BrowserRouter, useRoutes } from "react-router-dom"; // v6 beta

import Home from './pages/Home';

const App = () => {
  const Routes = () => useRoutes([{ path: "/", element: <Home /> }]);

  return (
    <BrowserRouter>
      <Routes />
    </BrowserRouter>
  );
};

export default App;

Just want to report on a similar issue -- as of writing (v6.2.1), it seems you actually encounter this error as well if you are importing from react-router instead of react-router-dom .只是想报告一个类似的问题——在撰写本文时(v6.2.1),如果您从react-router而不是react-router-dom导入,您似乎也确实遇到了这个错误。 A costly typo on my part.对我来说是一个代价高昂的错字。

Ie, make sure you are importing Routes and Route from react-router-dom and NOT react-router即,确保您从react-router-dom导入RoutesRoute而不是react-router

// This is deceptively valid as the components exist, but is not the intended usage
import { Routes, Route } from 'react-router';

// This works and is the intended usage
import { Routes, Route } from 'react-router-dom';
> Following codes works since react-router-dom syntax changed because of React 18.

  import logo from './logo.svg';
    import './App.css';
    import Header from './components/Header';
    import Login from './components/Login';
    import {
      BrowserRouter as Router,
      Routes,
      Route,
      useRoutes,
    } from 'react-router-dom';
    import Signup from './components/Signup';
    
    function AppRoutes() {
      const routes = useRoutes(
        [
          {path:'/',element:<Login/>},
          {path:'/signup',element:<Signup/>}
        ]
      )
      return routes;
    }
    function App(){
      return (
        <Router>
          <Header/>
          <AppRoutes />
        </Router>
      )
    }
    
    export default App;

Try尝试

const Routes = () => useRoutes([]) 

and then wrap it like this in App.js然后在 App.js 中像这样包装它

<BrowserRouter> 
    <Routes />
</BrowserRouter>

It worked for me它对我有用

Try to add your routes in index.js not in App.js.尝试在 index.js 中添加你的路由,而不是在 App.js 中。 Your App.js is called from index.js.您的 App.js 是从 index.js 调用的。 In the index.js your external page is called like this在 index.js 你的外部页面是这样调用的

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Navbar />} />
      </Routes>
    </BrowserRouter>
  </React.StrictMode>
);

暂无
暂无

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

相关问题 (反应路由器 v6)“错误:useNavigate() 只能在<router>特定组件中的组件”错误</router> - (react router v6) "Error: useNavigate() may be used only in the context of a <Router> component" error in hoc component 错误:useRoutes() 只能在<Router>零件 - Error: useRoutes() may be used only in the context of a <Router> component React Router V6 - useNavigate() 只能在一个上下文中使用<router>零件</router> - React Router V6 - useNavigate() may be used only in the context of a <Router> component 反应路由器错误“useRoutes()只能用于<router>成分。”</router> - React router error "useRoutes() may be used only in the contect of a <Router> component." 错误: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 使用 React Router V6 和 useRoutes 进行模块化路由? - Modular Routing with React Router V6 and useRoutes? React Router V6 - useRoutes() 路径正则表达式 - React Router V6 - useRoutes() Path Regex react-router-dom v6 使用路由 - react-router-dom v6 useRoutes React js:错误:useLocation()只能在a的上下文中使用<router>成分</router> - React js: Error: useLocation() may be used only in the context of a <Router> component 未捕获的错误:useNavigate() 只能在<router>组件 [react-router-dom 6.4]</router> - Uncaught Error: useNavigate() may be used only in the context of a <Router> component [react-router-dom 6.4]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM