- 引入路由管理,是針對項目中存在多個不同的,或者多層級的頁面的一種比較好的解決方法,沒有路由也不是不可以做,就是管理起來不是很方便。
- 要注意一下,當
react-router
升級到4.0以后就不再支持Route
的多級嵌套了,所以每次存在子路由的時候,可能需要一個公共的父級頁面來專門渲染子路由。
- 首先是在
routes
文件夾下添加對應的路由配置文件。import { AsyncComponent } from 'Utils/component';
const Main = AsyncComponent(() => import('Pages/main'));
const Home = AsyncComponent(() => import('Pages/Home'));
const HelloWorld = AsyncComponent(() => import('Components/test/HelloWorld'));
const routes = [
{
path: '/',
component: Main,
exact: true // 嚴格匹配,保證剛進來的時候直接展示首頁
},
{
path: '/',
component: Home, // 模糊匹配,進入子路由的時候,就會走這里
children: [
{
path: '/hello',
component: HelloWorld
}
]
}
];
export default routes;
- 然后是多路由的渲染,我將其抽離出來,方便后續可以增加功能,比如可以將全局的search參數做處理后傳入路由對應的組件,方便使用
/**
* 路由遍歷功能
*/
const renderRoutes = (routes) => {
return routes.map((route, index) => {
const { children, path, exact = false } = route;
/**
* 可以在這里做一些全局的處理,把search參數處理之后傳進route.component,這樣就不用每個頁面都要對search參數去做一次處理
*/
const search = location.search;
const query = searchToQuery(search); // 將search字符串變成一個對象,然后傳入
return (
<Route
path={path}
exact={exact}
key={`${route.path}-${index}`}
render={props => <route.component {...props} routes={children} urlQuery={query} />}
/>
)
})
}
- 在入口文件
index.js
中使用路由。import React from "react";
import ReactDOM from "react-dom";
import { Router } from 'react-router';
import { createBrowserHistory } from 'history';
import { renderRoutes } from 'Utils/component';
import routes from 'Routes';
const browserHistory = createBrowserHistory();
// 使用browserHistory有一個注意點,本地開發時,需要將webpack的config.devServer.historyApiFallback設置為true。不然會出現你輸入路徑時,把路徑當做接口來訪問,而不是當做路由。
function render() {
ReactDOM.render(
<Router history={browserHistory}>
{
renderRoutes(routes)
}
</Router>,
document.getElementById("root")
);
}
render();
- 至此,我們的異步加載組件和多級路由全部加入,下一次就是配置redux。