【问题标题】:Uncaught (in promise) TypeError: Cannot call a class as a function未捕获(承诺中)TypeError:无法将类作为函数调用
【发布时间】:2019-01-08 23:51:24
【问题描述】:

我最近将我的 babel 版本升级到了最新版本。更新后,我的反应应用程序中的 babel 无法识别普通类,并且我遇到了错误。

Uncaught (in promise) TypeError: Cannot call a class as a function

.babelrc

{
  "presets": [
    "env", 
    "react"
  ],
  "plugins": [
    "transform-class-properties",
    "transform-object-rest-spread"
  ]
}

我的应用中的 babel 相关库:

"babel-core": "^6.26.3",
"babel-eslint": "^8.2.6",
"babel-jest": "^22.4.3",
"babel-loader": "^7.1.5",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-plugin-transform-object-rest-spread": "^6.26.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1"

babel 不理解这个类

CRUDTree.js

const resourceBoxWidth = 225;
const resourceBoxHeight = 85;
const halfBoxWidth = resourceBoxWidth / 2;
const halfBoxHeight = resourceBoxHeight / 2;
const urlLeftMargin = 10;
const urlFontSize = 12;
const fullPathFontSize = 10;
export default class{
  static resourceBoxWidth() { return resourceBoxWidth; }
  static resourceBoxHeight() { return resourceBoxHeight; }
  static halfBoxHeight() { return halfBoxHeight; }
  static halfBoxWidth() { return halfBoxWidth; }
}

APITree.js

import React, { Component } from 'react';
import CRUDTree from './CRUDTree';

class extends Component{
render(){
return(
  <CRUDTree data={
                [
                  this.state.treedata,
                  this.onClick,
                  {
                    x: this.state.offsetX,
                    y: this.state.offsetY
                  }
                ]}
              width={400} height={500}
              options={{
                border: "2px solid black",
                margin: {
                  top: 0,
                  bottom: 0,
                  left: 50,
                  right: 0
                }
              }
              } />
)
}
}

【问题讨论】:

  • 我认为问题在于你调用这个类的方式,你能告诉我们吗?
  • 当然。我更新了我的问题。请检查

标签: reactjs ecmascript-6 environment-variables babeljs babel-loader


【解决方案1】:

如果您的 CRUDTree 是一个 React 组件(在我看来就是这样),那么您的定义是错误的。您缺少 extends 部分。

export default class extends React.Component {
    ....
}

【讨论】:

  • 我同意你的看法。
  • 不,它不反应组件。它的普通类不扩展 React 组件。请检查我更新的问题。在更新到最新的 babel 版本和 webpack 到 4 之前,没有扩展 React.Component 的同一个类工作得非常好。
  • 当我们谈论类时,我仍然是个菜鸟,并且对 React 仍然不是很好,但是您正在导出一个类并尝试在这里将其用作常规 React 组件? React 组件等待函数返回而不是类。我们不是定义一个类并从中创建一些新实例吗?您正在使用此类作为组件并向其传递一些道具。你在哪里使用这些道具?请原谅我缺乏信息,但这种用法在我看来仍然很奇怪。我当然不知道这是如何工作的。
  • 同意你的观点 devserkan 我在这部分也很困惑,但旧代码在我的开发环境中运行良好。在我将 webpack 和 babel 升级到最新版本后,这个问题开始出现。如果我分享你的 webpack 配置和 webpack 版本细节会有帮助吗
  • 没问题,我很高兴你以某种方式解决了它。我们每天都会犯愚蠢的错误:)
猜你喜欢
  • 2018-10-21
  • 2022-11-11
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 2023-02-21
  • 2019-01-10
  • 1970-01-01
  • 2018-07-04
相关资源
最近更新 更多