使用create-react-app进行中后台开发(二、引入路由)
引入路由的意义在于当我们访问不同的url时,react所构造的单页面应用能够进行相应的跳转,展示我们设置的子页面。
1、安装react-router-dom,目前版本是V6
官网地址:https://reactrouterdotcom.fly.dev/docs/en/v6/getting-started/tutorial
npm install react-router-dom@6 history@5
2、在my-app项目的src目录下建立我们自己的页面结构:新建pages/home ;pages/errorr,并且在对应的目录下创建对应的js文件。
例如:home.js
function Home() { return ( <div className="Home"> home page </div> ); } export default Home;
3、在router.js中配置路由:
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
import Home from '../pages/home/home';
import User from '../pages/user/user';
import Error from '../pages/error/error';
function Router(){
return(
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />}>
<Route path="user" element={<User />}/>
<Route path="home" element={<Home />}/>
</Route>
<Route path="/error" element={<Error/>}/>
</Routes>
</BrowserRouter>
);
}
export default Router;
4、在入口文件index.js中引入路由:
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import reportWebVitals from './reportWebVitals'; import Router from './router/router'; ReactDOM.render( <React.StrictMode> <Router/> <App /> </React.StrictMode>, document.getElementById('root') ); // 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();
5、访问url: