gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:29:04 33 4
gpt4 key购买 nike

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

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com