【问题标题】:Webpack imported class' function is undefinedWebpack 导入类的函数未定义
【发布时间】:2018-07-18 07:17:33
【问题描述】:

使用导入类中的函数时,我从 webpack 收到 TypeError。

我收到TypeError: __WEBPACK_IMPORTED_MODULE_6_clients_FilesClient__.a.upload(...) is undefined

我正在导出我的课程:

export default(FilesClient = new FilesClient());

并将其导入到我的组件中:

import FilesClient from "clients/FilesClient";

当我这样使用客户端时:

acceptedFiles.forEach(file => {
    FilesClient.upload(file, this.props.proposalId)
    .then(data => {
    ....

类型错误被抛出。我不确定这是为什么...我能够将对象和函数记录到控制台并且请求成功发出,但是反应应用程序在响应恢复正常之前崩溃了。

这与我导出/导入其他几个客户端的方式相同,但是到目前为止我只使用这些客户端发出 GET 请求……不知道为什么这个会搞砸。我可以把这个函数从这个客户端类中拿出来就可以了,只是想弄清楚Webpack的问题。

仅供参考,这里是 Webpack 所说的未定义函数的类:

import Client from "./Client";

class FilesClient extends Client {
  upload = (file, proposalId) => {
    const url = `/api/proposals/${proposalId}/uploadfile`;

    let formData = new FormData();
    formData.append("file", file, file.name);

    fetch(url, {
      method: "POST",
      body: formData
    }).then(response => {
      if (!response.ok) {
        console.log(response);
        throw Error("File upload failed", response);
      }
      return response.json();
    });
  }
}

export default (FilesClient = new FilesClient());  

提前致谢!

【问题讨论】:

    标签: reactjs webpack ecmascript-6 babeljs


    【解决方案1】:
    export default new FilesClient();
    

    试试这个它应该会给你想要的结果,你现在做的事情是错误的,因为它是一个赋值,它什么也不返回。

    这里是codeandbox链接 example

    【讨论】:

    • 我编辑了您的示例以反映我如何使用我的类并且它工作正常...我还能够以相同的方式导入和使用另一个具有 getter 函数的客户端。所以它似乎与这个 FilesClient 类是隔离的。 Edited Example
    • 我确实尝试了您的解决方案,但仍然以同样的方式出错
    猜你喜欢
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多