主要 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
的使用去掉,增加 createBrowserRouter
、RouterProvider
的相关设置
-
createBrowserRouter
创建路由 - 挂载到
RouterProvider
的router
上
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;
然后就完成啦~