安装路由
npm install react-router-dom@5.2.0 --save-dev
创建基础页面
Home、Ddetail、Error页面等
如Error.js
import React, { Component } from 'react'
export default class Error extends Component{
render(){
return(<div>
404
</div>)
}
}
路由配置
可以创建一个 routerConfig.js 的文件,专门用来做路由配置:
routerConfig.js:
import Home from './Home'
import List from './List'
import Error from './Error'
const routerConfig = [
{pathname: "/home", component: Home, exact: true},
{pathname: "/list", component: List, exact: true},
{pathname: "*", component: Error, exact: false}
]
export default routerConfig
然后引入到 router.js 中,如:
import React, { Component } from 'react'
import { BrowserRouter, Route, Switch} from 'react-router-dom'
import routerConfig from './routerConfig'
export default class BasicRoute extends Component {
render() {
return (
<BrowserRouter>
<Switch>
{routerConfig.map((item, index) => {
console.log(item.pathName);
return (
<Route exact={item.exact} path={item.pathName} component={item.component} key={index} />
)
}
)}
</Switch>
</BrowserRouter>
)
}
}
在 index.js 中引入:
// 1.引入模块
import React from 'react'
import { createRoot } from 'react-dom/client'
import Router from './router' //引入router
const root = createRoot(document.getElementById('root'));
root.render(
<div>
<Router />
</div>
)