问题描述
我已经安装了 react-router-dom
V6-beta.通过遵循网站上的示例,我可以使用新选项 useRoutes
我设置了页面路由并在 App.js
文件中返回它们.
I have installed 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() 只能在组件的上下文中使用.
我想知道我是否在这里遗漏了什么?我在 src/pages
文件夹中创建了页面.
I am wondering If I am missing something here? I have created the pages inside the src/pages
folder.
我的代码:
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
元素内.
It think the problem is that you still need to wrap routes
(Routes
/ useRoutes
) inside a Router
element.
所以一个例子看起来像这样:
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.
这篇关于React Router V6 - 错误:useRoutes() 只能在 <Router> 的上下文中使用.零件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论