我已安装 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/