React Router v6(关于Use useRoutes instead of react-router-config)

2,777 阅读1分钟

1. 官方文档的一些东西

All of the functionality from v5's react-router-config package has moved into core in v6. If you prefer/need to define your routes as JavaScript objects instead of using React elements, you're going to love this.

function App() {
  let element = useRoutes([
    // These are the same as the props you provide to <Route>
    { path: "/", element: <Home /> },
    { path: "dashboard", element: <Dashboard /> },
    {
      path: "invoices",
      element: <Invoices />,
      // Nested routes use a children property, which is also
      // the same as <Route>
      children: [
        { path: ":id", element: <Invoice /> },
        { path: "sent", element: <SentInvoices /> }
      ]
    },
    // Not found routes work as you'd expect
    { path: "*", element: <NotFound /> }
  ]);

  // The returned element will render the entire element
  // hierarchy with all the appropriate context it needs
  return element;
}

Routes defined in this way follow all of the same semantics as <Routes>. In fact, <Routes> is really just a wrapper around useRoutes.

We encourage you to give both <Routes> and useRoutes a shot and decide for yourself which one you prefer to use. Honestly, we like and use them both.

If you had cooked up some of your own logic around data fetching and rendering server-side, we have a low-level matchRoutes function available as well similar to the one we had in react-router-config.

Router从v.5升级到v.6会使用useRoutes而不再使用react-router-config

2. 可能会出现的问题[Error: useRoutes() may be used only in the context of a component]

在v.6中,<Router>组件下必须紧跟<Routes>,同样的useRoutes也必须直接应用在<Router>之下

import WrapRoute from './router/wrapRoute';
            ...
      <Router>
        <WrapRoute />
      </Router>
import { useRoutes } from 'react-router';
import RouteConfigs from './routeConfig';

export default function WrapRoute() {
  const element = useRoutes(RouteConfigs)
  return element
}
//页面,子页面
import Home from '../components/Home/Home';
...
import { Userlist } from '../pages/UserList/userlist'


const RouteConfigs = [
  {
    path: "home", element: <Home />,
    children: [
      { path: "test1", element: <Test1 /> },
      { path: ":test", component: <Test2 /> }
    ]
  },
  {
    path: "react-home", element: <ReactHome />,
    ...
]

RouteConfigs其实可以直接写到WrapRoute组件中

3 v.5 react-router-config的使用

浅析react-router-config的使用 - 掘金 (juejin.cn)