react 项目路由配置(react-router-dom 版本 v6.3、v6.4)-二、react-router-dom v6.

时间:2024-04-24 18:52:29

主要 api:

  • createBrowserRouter
  • RouterProvider
  • Outlet

在 v6.3 方案的基础上,换掉 index.js 和 App.js 即可

1、index.js

BrowserRouter 的使用去掉


import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";

// v6.3 使用此API,v6.4使用会报错
// import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  // <BrowserRouter>
  <React.StrictMode>
    <App />
  </React.StrictMode>
  // </BrowserRouter>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

2、App.js

useRoutes 的使用去掉,增加 createBrowserRouterRouterProvider 的相关设置

  • createBrowserRouter 创建路由
  • 挂载到 RouterProviderrouter

import React from "react";
import routes from "./routes";

// v6.3 userRoutes钩子
// import { useRoutes } from "react-router-dom";
// const App = () => {
//   const element = useRoutes(routes);
//   return <>{element}</>;
// };

// v6.4 createBrowserRouter + RouterProvider
import { createBrowserRouter, RouterProvider } from "react-router-dom";
const router = createBrowserRouter(routes);
const App = () => {
  return (
    <>
      <RouterProvider router={router} />
    </>
  );
};

export default App;

然后就完成啦~