關(guān)于react-router的大部分資料可以從官方文檔中獲取
https://reacttraining.cn/web/guides/quick-start
這里寫幾點(diǎn)自己從v3 升級(jí)到v4時(shí)候出現(xiàn)的問題
1.代碼拆分:
官方上給的事例是自己實(shí)現(xiàn)一個(gè)bundle類,使用
bundle-loader?lazy!./Something 和webpack實(shí)現(xiàn)代碼拆分,這種方式在寫的時(shí)候略有麻煩,可以自己更改bundle類實(shí)現(xiàn)更簡(jiǎn)單的。這里提供一個(gè)方法:
使用import LazyRoute from 'lazy-route'
path: '/customer/detail/',
breadcrumbName: '客戶管理/詳情',
exact: true,
render: (props) => <LazyRoute {...props} component={import('./containers/customer/Detail')}/>
這樣一個(gè)配置,就可以達(dá)到代碼拆分的效果且寫起來比較美觀
2.權(quán)限檢測(cè):
權(quán)限檢測(cè)目前在項(xiàng)目中沒有找到一個(gè)好的方式去實(shí)現(xiàn)異步檢測(cè),目前是將權(quán)限獲取到本地進(jìn)行同步檢測(cè),在v4中和v3的方式完全不同。v3 中路由有鉤子,而在v4中取消了該方法,總體我們可以自己封裝router類來實(shí)現(xiàn):
const PrivateRoute = ({component: Component, ...rest}) => (
<Route {...rest} render={props => {
return (
api.isLogin() ?
auth(props.match.path) ? (
<Component {...props}/>
) : (
<Redirect to={{
pathname: '/permission-403',
state: {from: props.location}
}}/>
) : (
<Redirect to={{
pathname: '/login',
state: {from: props.location}
}}/>
)
)
}}/>
);
export default PrivateRoute;
3.router 配置文件
v4中推薦配置文件配置路由,先將路由寫在一個(gè)配置文件中,在需要展示的地方map出來
const routers = [{
path: '/',
breadcrumbName: "首頁/",
exact: true,
render: () => api.isLogin() ? <Redirect to="/home"/> : <Redirect to="/login"/>,
}, {
path: '/home',
exact: true,
breadcrumbName: "首頁/",
render: () => api.isHeadquarters() ? <OverView/> : <Home/>,
}, {
path: '/customer/detail/',
breadcrumbName: '客戶管理/詳情',
exact: true,
render: (props) => <LazyRoute {...props} component={import('./containers/customer/Detail')}/>
}, {
path: '/customer/detail/:customerId',
breadcrumbName: '客戶管理/詳情',
exact: true,
render: (props) => <LazyRoute {...props} component={import('./containers/customer/Detail')}/>
}]
routes.map((route, index) => (
<PrivateRoute
key={index}
path={route.path}
exact={route.exact}
component={route.render}
/>
配置文件可以寫多個(gè)組件,在一個(gè)頁面我們可以顯示一個(gè)路由中的不同組件,比如sideBar breadcrumbName等等。
配置文件不能寫空路由,即沒有定義組件的路由,這樣在渲染的時(shí)候因?yàn)槠ヅ涞搅寺酚啥荒茕秩緐ndefined組件報(bào)錯(cuò)。
更多的信息可以見文檔。官方文檔寫的比較簡(jiǎn)潔,從v3版本升級(jí)會(huì)遇到坑。