react-router4踩坑一:react-loadable的配置

react-router4中使用react-loadable进行组件的懒加载和代码分割。不同于以往的版本的react-router,react-loadable将react的组件化思想贯彻到底,其懒加载即使用react-loadable创建一个懒加载的组件。

刚开始使用的时候我仿照官方的事例对自己开发的需要懒加载的组件进行处理:

```
// Dashboard
const LoadableDashboard = Loadable({
  loader: () => import('../Dashboard'),
  loading: Loading
});

export class Dashboard extends React.Component {
  render() {
    return 
  }
}

但在使用过程中发现react-loadable和路由一同使用时,在组件会获取不到路由的match属性,调用match.isExact时报错,报错的代码部分如下:

const {match, changeSidebar} = this.props;
if (match.isExact) {
  changeSidebar('charts');
}

使用react-loadable之前可以正常获取exact属性,而在使用react-loadable包裹需要懒加载的组件后exact属性便无法获取。在网上没有找到解决方案,思考后发现:
1. react-router4中每个路由也是一个组件,exact属性是从路由组件中传递给子组件的props
2. react-loadable创建了新的懒加载组件包裹了原组件,而组件又包裹了react-loadable生成的组件
3. 所以问题就在于react-loadable生成的中间组件影响了react-router4的路由组件向我们的子组件传递props,所以要传递props给子组件,修正代码如下:

// Dashboard
const LoadableDashboard = Loadable({
  loader: () => import('../Dashboard'),
  loading: Loading
});

export class Dashboard extends React.Component {
  render() {
    return     // 传递props
  }
}

传递props后即可顺利获得match属性,用以判断路由的匹配情况。

你可能感兴趣的:(React,React-Router,React)