Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/465.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 从另一个函数调用函数_Javascript_Reactjs_Dropzone.js - Fatal编程技术网

Javascript 从另一个函数调用函数

Javascript 从另一个函数调用函数,javascript,reactjs,dropzone.js,Javascript,Reactjs,Dropzone.js,在设置了一个简单的图像上传后,我试着从一个函数调用另一个函数,然后日志就出来了 未处理的拒绝(TypeError):self.sendImage不是函数 这是代码 readFile(files) { var self = this; if (files && files[0]) { let formPayLoad = new FormData(); formPayLoad.append("attachment_image",

在设置了一个简单的图像上传后,我试着从一个函数调用另一个函数,然后日志就出来了

未处理的拒绝(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,并且仍然保留错误

那么,有人能澄清一下为什么这会导致拒绝吗?
是否与类Es6相关?

您可能需要在构造函数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())

  }

您是否在构造函数中绑定了
sendImage
?此代码是类的一部分吗?
readFile
是如何调用的?@AndrewL不,我必须?@trincot我想是的,是从dropzone onDrop={this.readFile}调用的。问题是dropzone将调用
readFile
,而不将
this
设置为您的对象。请参阅重复参考以阅读有关此
的所有信息。有几种解决方案。一个是做
onDrop={this.readFile.bind(this)}
onDrop={()=>this.readFile()}
谢谢我会检查的,如果有帮助,请告诉我!Jacob Bralish谢谢你的工作!