doubleyong
管理员
管理员
  • 最后登录2025-02-06
  • 发帖数1196
  • 最爱沙发
  • 喜欢达人
  • 原创写手
  • 社区居民
  • 忠实会员
阅读:2861回复:0

[前端]useRoutes() may be used only in the context of a <Router> component.

楼主#
更多 发布于:2022-07-30 10:12
useRoutes如下方法使用时,
报错:
useRoutes() may be used only in the context of a <Router> component.


import { BrowserRouter as Router, useRoutes } from 'react-router-dom';
function App() {
  const routes = useRoutes([
    {
      path:'/',
      element: &lt;div&gt;...&lt;/div&gt;
    },
    {
      path:'/a', 
      element: &lt;div&gt;aaa&lt;/div&gt;
    }
  ]);
  return (
    &lt;Router&gt;
      {routes}
    &lt;/Router&gt;
  )
}


解决方案,以组件的方法使用
import { BrowserRouter as Router, useRoutes } from 'react-router-dom';
const GetRoutes = () =&gt; {
  const routes = useRoutes([
    {
      path:'/',
      element: &lt;div&gt;...&lt;/div&gt;
    },
    {
      path:'/a', 
      element: &lt;div&gt;aaa&lt;/div&gt;
    }
  ]);
  return routes;
}
const SetRoutes = () =&gt; {
  return (
    &lt;Router&gt;
      &lt;GetRoutes /&gt;
    &lt;/Router&gt;
  )
}
知识需要管理,知识需要分享
游客


返回顶部

公众号

公众号