反应路由器代码拆分 - 加载块之后/之前的事件

时间:2016-08-05 11:14:20

标签: javascript reactjs webpack react-router

如何获取有关反应路由器调用getComponent的事件并使用加载的组件调用回调?代码示例:

export default (store) => ({
  path: 'somepath',
  getComponent (nextState, cb) {
    require.ensure([], (require) => {
      const Container = require('./containers/Main').default
      cb(null, Container)
    }, 'module1')
  }
})

显然,我可以在require之前和之后放置函数,但这种方法不可扩展。我试着像这样制作代理,但得到错误Uncaught (in promise) TypeError: __webpack_require__(...).ensure is not a function(…)

function requireModule(callback, moduleName) {
  return (store) => {
    // before
    require.ensure([], (require) => {
      // after
      callback(require)
    }, moduleName)
  }
}


export default (store) => ({
  path: 'somepath',
  getComponent (nextState, cb) {
    requireModule((require) => {
      const Container = require('./containers/Main').default
      cb(null, Container)
    }, 'module1')(store)
  }
})

毕竟,我尝试使用react-proxy-router并获得2个错误,但渲染renderUnavailable模板。错误:

Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of `ComponentProxy`.

Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of `ComponentProxy`.

代码:

export default (store) => ({
  path: 'somepath',
  getComponent (nextState, cb) {
    var ComponentProxy = React.createClass({
        mixins: [require("react-proxy!./containers/Main").Mixin],
        renderUnavailable: function() {
            return <p>Loading...</p>;
        }
    });

    cb(null, ComponentProxy)
  }
})

0 个答案:

没有答案