- 首先创建Router/index.js,eg:包含Home和Login
import Home from '../Pages/Home/Home.jsx'
import Login from '../Pages/Login/Login.jsx'
let routes = [
{path: '/', component: Home, exact: true},
{path: '/login', component: Login},
]
export default routes
- 在App.js中引入:
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import routes from './Router/index'
// 路由页面
import Home from './Pages/Home/Home.jsx';
import Login from './Pages/Login/Login.jsx';
class App extends Component {
constructor(props) {
super(props);
this.state = { }
}
render() {
return (
<Router>
<ul className="topBar">
<li><Link to="/">Home</Link></li>
<li><Link to="/login">Login</Link></li>
</ul>
{
routes.map ((route, key) => {
// console.log(route)
if(route.exact) {
return (
<Route
key = {key}
exact
path = {route.path}
render = {props => (
<route.component {...props} />
)}
/>
)
}else{
return (
<Route
key = {key}
path = {route.path}
render = {props => (
<route.component {...props} />
)}
/>
)
}
})
}
</Router>
);
}
}
export default App;
到此,动态路由配置完成。