Asf*_*red 4 javascript reactjs
在下面的代码中:
handleImageChange = (newFile, crop) => {
var string = RandomString.generate(20);
newImage(string, newFile, this.state.type, 0)
.then((result) => {
if(result) {
this.toggleModal();
}
});
}
saveCropped() {
var values = this.cropper.values();
var crop = this.cropper.crop();
var newFile = convertBase64ToFile(crop);
setTimeout(function() {
this.handleImageChange(newFile, crop);
}.bind(this), 5000);
}
Run Code Online (Sandbox Code Playgroud)
saveCropped()调用的handleImageChange函数是调用函数。
这个函数的作用(newImage)是向我的服务器发送一个 Axios 请求,但是当我运行它时,我收到以下错误:“TypeError: Object(...)(...) is undefined”
问题是,即使我收到这个错误,代码在后台执行也没有问题,即请求被发送到我的服务器,我在控制台中得到了响应。
错误指向第 5 行(newImage(...))。
newImage 函数之所以起作用,是因为这不是它被调用的唯一地方,而且该函数只返回一个布尔值;即便如此,它仍然是:
function newImage(image_ID, image, imgType, type) {
var url = ...;
const header = {
headers: {
'Content-Type': imgType
}
};
axios.post(url, image, header)
.then(function (response) {
if(response.status === 200) {
if(type !== '1')
sessionStorage.setItem('avatar', image_ID);
console.log("Image uploaded!");
return true;
}
else
return false;
})
.catch(function (error) {
console.log(`Image could not be uploaded due to:\n${error}`);
return false;
});
}
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?
您正在尝试调用then()… 的返回值,newImage()但该函数没有 return 语句。
想必,您想返回通过调用返回的承诺axios.post:
return axios.post(url, image, header).
etc etc
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4567 次 |
| 最近记录: |