1、安裝 react-router-dom
yarn add react-router-dom --save
2、新建router文件夾
-src
--router(文件夾新建)
---index.js
---routes.js
-App.js (腳手架自帶)
3、src/router/index.js
(未配置多層級路由,后續優化) //引入react jsx寫法的必須 import React from 'react'; // 引入路由配置 import routes from "./routes"; //引入一些模塊 import { BrowserRouter as Router, Route} from "react-router-dom"; function router(){ return ( <Router> { routes.map(router=>{ return ( <Route path={ router.path } component = { router.component } ></Route> ) }) } </Router> ); } export default router;
4、src/router/routes.js
(未使用組件懶加載,后續優化)
//引入需要用到的頁面組件
import Home from './pages/home';
import About from './pages/about';
const routers = [
{
path:'/home',
component:Home
},
{
path:'/about',
component:About
}
]
export default routers
4.1、/pages/home
import React from 'react'; const Home = () => { return( <div> Home </div> ) } export default Home
4.2、/pages/about
import React from 'react'; const About = () => { return( <div> About </div> ) } export default About
5、App.js
import React from 'react'; import Router from './router'; function App() { return ( <div className="App"> <Router/> </div> ); } export default App;
6、在路由中輸入
http://localhost:3000/home
http://localhost:3000/about
可實現查看不同頁面
至此,基本的路由已經配置完成!
有什么優化的地方,歡迎評論