1、先看一下未模块化的路由配置,有哪些地方是可以提出去的
import React from 'react'
import '../css/index.css'
import { BrowserRouter as Router, Route, Link} from 'react-router-dom'
/********************这一块是可以单独提出去的 start**************************/
import EntryPage from '../components/entryPage'
import DownloadPage from '../components/downloadPage'
let routes = [
{
path: '/',
components: EntryPage,
exact: true
},
{
path: '/download',
components: DownloadPage
}
]
/********************这一块是可以单独提出去的 end**************************/
class App extends React.Component{
render() {
return (
<Router>
<div id="app">
/**********************这是导航 start***************************/
<Link to="/">EntryPage</Link>
<Link to="/download">download</Link>
/**********************这是导航 end***************************/
/**********************这一块可以处理为循环遍历 start***************************/
<Route path='/' component={EntryPage}/>
<Route path='/download' component={DownloadPage}/>
/**********************这一块可以处理为循环遍历 end***************************/
</div>
</Router>
);
}
}
export default App;
2、模块化后
1、新建router.js文件,用于配置路由
import EntryPage from '../components/entryPage'
import DownloadPage from '../components/downloadPage'
let routes = [
{
path: '/',
components: EntryPage,
exact: true
},
{
path: '/download',
components: DownloadPage
}
]
export default routes;
2、上面的文件改为
import React from 'react'
import '../css/index.css'
import { BrowserRouter as Router, Route, Link} from 'react-router-dom'
import routes from '../utils/router' // 这个为新建的router.js
class App extends React.Component{
render() {
return (
<Router>
<div id="app">
<Link to="/">EntryPage</Link>
<Link to="/download">download</Link>
{
routes.map((item,key)=> {
if (item.exact) {
return <Route key={key} exact path={item.path} component={item.components}/>
} else {
return <Route key={key} path={item.path} component={item.components}/>
}
})
}
</div>
</Router>
);
}
}
export default App;
这样就好了,后面再添加新的路由,只需要修改router.js的配置参数就行。
导航也可以改为循环遍历的方式,不过需要在router.js的配置项下加上导航的字段,比如:{ path: '/', components: EntryPage, exact: true, name: 'EntryPage' },
另外路由的跳转处理以Link方式作为导航外,还可以通过this.props.history.push('/')
跳转,例如:<button onClick={()=>this.props.history.push('/')}>回到首页</button>
来源:CSDN
作者:codeXml
链接:https://blog.csdn.net/qq_39905409/article/details/104173027