react-router-config主要用来帮助我们进行集中式路由的配置,在不使用react-router-config之前,我们的路由使用react-router-dom库来进行配置,类似如下代码:
import React from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
} from "react-router-dom";
import Home from './pages/Home';
import Login from './pages/Login';
import Backend from './pages/Backend';
import Admin from './pages/Admin';
function App() {
return (
<Router>
<Switch>
<Route path="/login" component={Login}/>
<Route path="/backend" component={Backend}/>
<Route path="/admin" component={Admin}/>
<Route path="/" component={Home}/>
</Switch>
</Router>
);
}
export default App;
react-router-config可以使得路由配置更加简便
routes.ts路由配置
import { RouteConfig } from 'react-router-config';
import Home from '../components/Home';
import Inquiry from '../components/Inquiry';
import Offer from '../components/Offer';
const routes: RouteConfig = [
{
path: '/',
component: Home,
routes: [
{
path: '/inquiry',
component: Inquiry
},
{
path: '/offer',
component: Offer
}
]
}
]
export default routes
index.js入口文件
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'mobx-react';
import './index.css';
import { renderRoutes } from 'react-router-config';
import { HashRouter } from 'react-router-dom';
import routes from './config/routes';
import stores from './stores/index';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<HashRouter>
<Provider {...stores}>
{renderRoutes(routes)}
</Provider>
</HashRouter>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
Home组件:
import React from 'react';
import { renderRoutes } from 'react-router-config';
const Home = (props: any) => {
const route = props.route;
return <div>
<div>this is Home page.</div>
{route && renderRoutes(route.routes)}
</div>
}
export default Home;
Inquiry组件:
import React from 'react';
const Inquiry = () => {
return <div>Inquiry</div>
}
export default Inquiry;
Offer组件
import React from 'react';
const Offer = () => {
return <div>Offer</div>
}
export default Offer;
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。