一、安装依赖
yarn add react-router-dom@5
yarn add react-router-config
注意:这里有个小坑,react-router-dom 在v5版本升级到v6版本有一些变换。 (1) Switch 重命名为 Routes (2) Route 的新特性变更 ,component/render 被element 替代 所以安装react-router-dom 需要安装5版本否则将会出现以下错误:
二、配置路由
import HYDiscover from "../pages/discover";
import HYFriend from "../pages/friend";
import HYMine from "../pages/mine";
const routes = [
{
path: "/",
exact: true,
component: HYDiscover,
},
{
path: "/mine",
component: HYMine,
},
{
path: "/friend",
component: HYFriend,
},
];
export default routes;
三、使用路由
import React, { memo } from "react";
import { renderRoutes } from "react-router-config";
import { HashRouter } from "react-router-dom";
import routes from "./router";
const App = memo(() => {
return (
<HashRouter>
{renderRoutes(routes)}
</HashRouter>
);
});
export default App;
|