NervJS / nerv

A blazing fast React alternative, compatible with IE8 and React 16.
https://nerv.aotu.io
MIT License
5.43k stars 267 forks source link

解决react-lifecycles-compat无法识别组件的问题 #89

Open lingxuan630 opened 6 years ago

lingxuan630 commented 6 years ago

https://github.com/reactjs/react-lifecycles-compat/blob/master/index.js#L53 在目前的版本,编译之后isReactComponent并不能在Component.prototype中找到,到时使用到react-lifecycles-compat的组件都无法在nerv正常运行。

yuche commented 6 years ago

有两个问题:

  1. 函数标识符之后要加空格符合 tslint 的规范;
  2. 变成一个函数之后应该结果是一样的?因为我看 react-lifecyle-compat 并没有调用 isReactComponent 这个函数。请问能否写一个简单的测试用例?
lingxuan630 commented 6 years ago

@yuche 修改isReactComponent = EMPTY_OBJ这一行主要是要解决编译后,isReactComponent并不能在Component.prototype中找到的问题,我附上当前版本编译后代码吧:

var Component = function Component(props, context) {
    this._dirty = true;
    this._disable = true;
    this._pendingStates = [];
    // Is a React Component.
    // tslint:disable-next-line:max-line-length
    // see: https://github.com/facebook/react/blob/3c977dea6b96f6a9bb39f09886848da870748441/packages/react/src/ReactBaseClasses.js#L26
    this.isReactComponent = EMPTY_OBJ;
    if (!this.state) {
        this.state = {};
    }
    this.props = props || {};
    this.context = context || EMPTY_OBJ;
    this.refs = {};
};

上面的明显不能通过Component.prototype.isReactComponent判断是否是组件。 我们再看react-lifecycles-compat的实现:

if (!prototype || !prototype.isReactComponent) {
    throw new Error('Can only polyfill class components');
 }

如果找不到prototype.isReactComponent就会抛出错误。引用了react-lifecycles-compat的组件都无法正常使用。

yuche commented 6 years ago

Component 类之外加一行 Component.prototype.isReactComponent = EMPTY_OBJECT 是不是更好?

这样可以应对有些库判断 isReactComponent 是一个对象的情况。