【问题标题】:Duplicate constructor in same class in JSX webpack buildJSX webpack构建中同一类中的重复构造函数
【发布时间】:2017-09-10 05:02:18
【问题描述】:

我写的一些代码有问题,这让我很困惑。

JSX Github Page 上的主要 JSX 教程有一个名为 Point 的示例类,如下所示:

class Point {
    var x = 0;
    var y = 0;

    function constructor() {
    }

    function constructor(x : number, y : number) {
        this.set(x, y);
    }

    function constructor(other : Point) {
        this.set(other);
    }

    function set(x : number, y : number) : void {
        this.x = x;
        this.y = y;
    }

    function set(other : Point) : void {
        this.set(other.x, other.y);
    }
}

该类有一个清晰的示例,其中包含我从 C++ 时代就熟悉的多种构造函数类型。它甚至有一个已定义的复制构造函数,我认为这很棒。

但是,如果我获得并创建了一个类似的类供我使用:

export default class MutableDataStore {
	constructor() {
		this.data = [];
		this.settings = {};
	}

	//Copy constructor
	constructor(other : MutableDataStore) {
		this.data = other.data.slice();
		this.settings = Object.assign({}, this.settings);
	}
  
  //...Other functions omitted
}

我在我的 webpack 构建中收到以下错误:

./src/stores/helper-classes/mutabledatastore.jsx 中的错误 模块构建失败:SyntaxError: Duplicate constructor in the same class (8:1)

我完全被这个难住了,因为我在网上找不到任何类似的东西,除非它似乎是一个暂时的问题。

我的 webpack.config.js 是:

var webpack = require("webpack");
var path = require("path");
 
var src = path.resolve(__dirname, "src");
var app = path.resolve(__dirname, "app");
 
var config = {
  entry: src + "/index.jsx",
  output: {
    path: app,
    filename: "javascript.js"
  },
  module: {
    loaders: [{
        include: src,
        loader: "babel-loader"
    }]
  }
};
 
module.exports = config;

我的 babel 预设是 es2015 和 react。

任何帮助将不胜感激!

【问题讨论】:

  • 命名很糟糕,但是“JSX”教程页面是针对某人制作的称为 JSX 的语言,但它不是 React 使用或 Babel 处理的 JSX。普通的 ES6 中不允许使用多个 constructor 函数,不管有没有 Babel/React 的 JSX。
  • @loganfsmyth 感谢您回答问题。我希望我能给你答案,因为这似乎完全回答了我的问题。

标签: reactjs constructor webpack babeljs jsx


【解决方案1】:

正如loganfsmyth 在cmets 中所说,可以有only be one constructor in an ES6 class。您可以通过检查构造中是否设置了 other 或为参数提供默认值来获得所需的效果

export default class MutableDataStore {
    constructor(other : MutableDataStore) {
        this.data = other ? other.data.slice() : [];
        this.settings = other ? Object.assign({}, other.settings) : {};
    }

  //...Other functions omitted
}

// or

export default class MutableDataStore {
    constructor(other : MutableDataStore = { data: [], settings: {} }) {
        this.data = other.data.slice();
        this.settings = Object.assign({}, other.settings);
    }

  //...Other functions omitted
}

另一方面,我认为您可能希望复制构造函数从 other 复制设置,而不是 this

【讨论】:

  • 谢谢,这很有用。看看别人是怎么做的很有趣。是的,我的意思是复制其他的设置,而不是这个......不接受答案,因为我的问题似乎特别混淆了在谷歌上高度链接的另一个 JSX 项目以及它给我的冲突信息。如果 JSX 是一种转译语言,那么人们可能会在其中添加类似的扩展,这似乎是合乎逻辑的。
  • 这些示例中的代码本质上不是 jsx。 react 上下文中的 jsx 是指在 javascript 代码中使用类似 HTML 的标签,例如render() { return <div>example</div> }。这些类是符合 ECMAScript 6 (ES6) 的 JavaScript。
猜你喜欢
  • 2015-12-01
  • 2023-04-03
  • 2012-06-22
  • 1970-01-01
  • 2020-02-15
  • 1970-01-01
  • 2023-03-13
  • 2014-08-01
  • 2011-02-15
相关资源
最近更新 更多