Javascript 从另一个函数调用函数
在设置了一个简单的图像上传后,我试着从一个函数调用另一个函数,然后日志就出来了 未处理的拒绝(TypeError):self.sendImage不是函数 这是代码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",
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谢谢你的工作!