前言
在react后台管理系统中使用router相关插件完成路由的集中管理和跳转,在这里记录一下
实现过程
下载react-router-dom
cnpm i -D react-router-dom
在nav组件中去写功能代码
// nav的index.js中
import {
Link } from 'react-router-dom'
<Link to={
item.key}>{
item.title}</Link>
此时会报错,需要在最外层加Route
// 在项目入口的index.js文件中
import {
BrowserRouter} from 'react-router-dom'
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
)
此时我们去点击左侧的导航菜单,页面路由就会发生改变。
这里我们下载一下react-router-config进行路由的集中管理
cnpm i -D react-router-config
下载完成后在src下新建一个router文件夹,文件夹中新建一个index.js,先写入一点内容:
// router文件夹下的index.js
import Home from '../pages/home'
const routes = [
{
path: '/',
exact: true,
component: Home
},
{
path: '/home',
exact: true,
component: Home
}
]
export default routes
然后去到app.js
import {
renderRoutes } from 'react-router-config'
import routes from './router'
{
/* <Home/> 这里替换成下面的方法*/}
{
renderRoutes(routes)}
效果
点击导航栏 路由地址就会跳转到对应的router