關(guān)于react-router的大部分資料可以從官方文檔中獲取
https://reacttraining.cn/web/guides/quick-start
這里寫幾點自己從v3 升級到v4時候出現(xiàn)的問題
1.代碼拆分:
官方上給的事例是自己實現(xiàn)一個bundle類塔猾,使用
bundle-loader?lazy!./Something 和webpack實現(xiàn)代碼拆分篙骡,這種方式在寫的時候略有麻煩,可以自己更改bundle類實現(xiàn)更簡單的丈甸。這里提供一個方法:
使用import LazyRoute from 'lazy-route'
path: '/customer/detail/',
breadcrumbName: '客戶管理/詳情',
exact: true,
render: (props) => <LazyRoute {...props} component={import('./containers/customer/Detail')}/>
這樣一個配置糯俗,就可以達(dá)到代碼拆分的效果且寫起來比較美觀
2.權(quán)限檢測:
權(quán)限檢測目前在項目中沒有找到一個好的方式去實現(xiàn)異步檢測,目前是將權(quán)限獲取到本地進(jìn)行同步檢測睦擂,在v4中和v3的方式完全不同得湘。v3 中路由有鉤子,而在v4中取消了該方法顿仇,總體我們可以自己封裝router類來實現(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中推薦配置文件配置路由忽刽,先將路由寫在一個配置文件中天揖,在需要展示的地方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}
/>
配置文件可以寫多個組件,在一個頁面我們可以顯示一個路由中的不同組件跪帝,比如sideBar breadcrumbName等等今膊。
配置文件不能寫空路由,即沒有定義組件的路由伞剑,這樣在渲染的時候因為匹配到了路由而不能渲染undefined組件報錯斑唬。
更多的信息可以見文檔。官方文檔寫的比較簡潔黎泣,從v3版本升級會遇到坑恕刘。