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
可实现查看不同页面
至此,基本的路由已经配置完成!
有什么优化的地方,欢迎评论