react-router v4注意事项

关于react-router的大部分资料可以从官方文档中获取

https://reacttraining.cn/web/guides/quick-start
这里写几点自己从v3 升级到v4时候出现的问题

1.代码拆分:

官方上给的事例是自己实现一个bundle类,使用
bundle-loader?lazy!./Something 和webpack实现代码拆分,这种方式在写的时候略有麻烦,可以自己更改bundle类实现更简单的。这里提供一个方法:
使用import LazyRoute from 'lazy-route'

  path: '/customer/detail/',
  breadcrumbName: '客户管理/详情',
  exact: true,
  render: (props) => <LazyRoute {...props} component={import('./containers/customer/Detail')}/>

这样一个配置,就可以达到代码拆分的效果且写起来比较美观

2.权限检测:

权限检测目前在项目中没有找到一个好的方式去实现异步检测,目前是将权限获取到本地进行同步检测,在v4中和v3的方式完全不同。v3 中路由有钩子,而在v4中取消了该方法,总体我们可以自己封装router类来实现:

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版本升级会遇到坑。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容