超级反应,无法读取未定义的 属性 'call'

react super, Cannot read property 'call' of undefined

我尝试在子方法中使用并覆盖父方法,但得到 Uncaught TypeError: Cannot read property 'call' of undefined

class BreadcrumbsHome extends React.Component {
  getBreadcrumbs = () => [{name: 'home', url: '/'}];

  render() {
    return <nav>
      <ol className="breadcrumb float-sm-right">
        {!!this.getBreadcrumbs && this.getBreadcrumbs().map((e, i, arr) =>
          <li className={`breadcrumb-item ${i === arr.length - 1 ? 'active' : ''}`}><a
            href={APP_CONTEXT + e.url}>{e.name}</a>/</li>
        )}
      </ol>
    </nav>
  }
}

class BreadcrumbsTypes extends BreadcrumbsHome {

  getBreadcrumbs = () => [
    ...super.getBreadcrumbs(),
    ...this.props.path
  ]

当我读到这个问题时。似乎与 babel 捆绑在一起,所以我尝试添加 //noprotect

我想用 ES6 处理并避免这种方式 ParentClass.prototype.myMethod.call(this, arg1, arg2, ..)

有什么解决办法吗?

如果你想保持JavaScript原型继承中预期的典型虚拟多态性,你不能使用字段初始化语法,你必须使用ES2015 class方法语法:

class BreadcrumbsHome extends React.Component {
  getBreadcrumbs () {
    return [{ name: 'home', url: '/' }];
  }

  render() {
    return <nav>
      <ol className="breadcrumb float-sm-right">
        {this.getBreadcrumbs().map((e, i, { length }) => (
          <li
            key={`${e.name}-${e.url}`}
            className={`breadcrumb-item ${i === length - 1 ? 'active' : ''}`}
          >
            <a href={APP_CONTEXT + e.url}>{e.name}</a> /
          </li>
        ))}
      </ol>
    </nav>
  }
}

class BreadcrumbsTypes extends BreadcrumbsHome {

  getBreadcrumbs () {
    return [
      ...super.getBreadcrumbs(),
      ...this.props.path
    ];
  }

  ...
}

问题是字段初始化器在每个 class 实例上创建自己的属性,而不是像 class 方法那样绑定到原型链,所以你所做的只是覆盖自己的 属性 getBreadcrumbs 由基础 class 初始化,自己的 属性 由扩展 class.

初始化

您可以使用调试器控制台确认这一点:

vs.

P.S。不要忘记在映射的 JSX 组件上包含一个唯一的 key 属性 :)

我还建议使用 CSS 来设置样式 .breadcrumb-item:last-child 而不是 .breadcrumb-item.active,这样您的 map() 回调可以将 className 简化为

className="breadcrumb-item"

您还可以将以下 class 添加到您的 CSS

.breadcrumb-item::after { 
  content: "/";
}

因此您可以在 JSX 中省略 /