【问题标题】:React call a function from another function [duplicate]React从另一个函数调用一个函数[重复]
【发布时间】:2018-12-09 20:21:40
【问题描述】:

设置简单的图像上传后,我尝试从函数中调用另一个函数并且日志吐出

未处理的拒绝(TypeError):self.sendImage 不是函数

这是代码

  readFile(files) {
        var self = this;
    if (files && files[0]) {
      let formPayLoad = new FormData();
      formPayLoad.append("attachment_image", files[0]);
      self.sendImage(formPayLoad);
    }

  }

  sendImage(formPayLoad) {
    let auth_token = window.localStorage.getItem("auth_token");
    fetch("/posts", {
      headers: {
        Accept: "application/json",
        Access: auth_token
      },
      method: "POST",
      body: formPayLoad
    })
      .then(response => response.json())

  }

为了修复它,我尝试将变量 this 更改为 self 并仍然存在错误。

所以,请有人能解释一下为什么这个 Unhandles Rejecton 吗? 和Es6类有关吗?

【问题讨论】:

  • 你在构造函数中绑定sendImage了吗?
  • 这段代码是类的一部分吗?以及readFile 是如何调用的?
  • @AndrewL 不,我必须?
  • @trincot 我认为是的,并且从 dropzone onDrop={this.readFile} 调用
  • 问题是 dropzone 将调用 readFile 而不将 this 设置为您的对象。请参阅重复参考以阅读有关 this 的所有信息。有几种解决方案。一种是做onDrop={this.readFile.bind(this)}onDrop={() => this.readFile()}

标签: javascript reactjs dropzone.js


【解决方案1】:

您可能需要在构造函数 ex 中绑定函数

this.sendImage = this.sendImage.bind(this);

或者你可以使用 ES6 并使用箭头函数来消除对箭头函数的需要

sendImage = (formPayLoad) => {
    let auth_token = window.localStorage.getItem("auth_token");
    fetch("/posts", {
      headers: {
        Accept: "application/json",
        Access: auth_token
      },
      method: "POST",
      body: formPayLoad
    })
      .then(response => response.json())

  }

【讨论】:

  • 谢谢你我会检查
  • 没问题,如果有帮助请告诉我!
  • Jacob Bralish 谢谢你的工作!
猜你喜欢
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多