React Router V6

编程入门 行业动态 更新时间:2024-10-21 23:21:32
本文介绍了React Router V6 - 错误:useRoutes() 只能在 <Router> 的上下文中使用.零件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经安装了 react-router-domV6-beta.通过遵循网站上的示例,我可以使用新选项 useRoutes 我设置了页面路由并在 App.js 文件中返回它们.

I have installed react-router-domV6-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() 只能在 &lt;Router&gt; 的上下文中使用.零件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-03-27 08:02:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/686626.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:React   Router

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!