reactjs - react 路由器 V6 - 错误 : useRoutes() may be used only in the context of a <Router> component

标签 reactjs react-router react-router-dom

我已安装 react-router-dom V6-测试版。通过遵循网站上的示例,我可以使用新选项 useRoutes我已经设置了页面路由并在 App.js 中返回它们文件。
保存后出现以下错误:
错误:useRoutes() 只能在组件的上下文中使用。
我想知道我是否在这里遗漏了什么?我在 src/pages 里面创建了页面文件夹。
我的代码:

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;

最佳答案

它认为问题在于您仍然需要包装routes ( Routes/useRoutes ) 在 Router 内元素。
所以一个例子看起来像这样:

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;
根据您的需要进行重构。

关于reactjs - react 路由器 V6 - 错误 : useRoutes() may be used only in the context of a <Router> component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65425884/

相关文章:

javascript - 在react-router-dom中使用条件渲染进行身份验证是否安全

node.js - node_modules/@types/错误(接口(interface) 'Element' 不能同时扩展类型 'ReactElement<any>)

javascript - 使用 React 的 useState 处理错误

javascript - 尝试导入错误 : 'makeStyles' is not exported from '@material-ui/core/styles'

reactjs - react-bootstrap 和 react-router 导致整页重新加载

react-router - react 路由器,匹配通配符作为参数

javascript - 如何在 React Router v6 中重定向?

google-maps - React-google-maps 重新渲染问题

reactjs - react : how can you share the state between views using react-router?

reactjs - 如何在具有 protected 功能的 React Router 中映射路由?