我試圖讓一個應用程序從api獲取回調,然後在函數中返回它(我不知道這是否合理)。但是我怎樣才能做到這一點,以便當我調用該函數時,我將一個回調附加到它上面,然後返回回調數據。這是非常混亂試圖描述它如此虐待試圖解釋,因爲我進入我的代碼...React - 組件中的回調
uploadToCloudinary(file){
const CLOUDINARY_URL = "MY_CLOUDINARY_URL";
const CLOUDIARY_UPLOAD_PRESET = "MY_CLOUDIARY_UPLOAD_PRESET"
let formData = new FormData();
formData.append("file", file);
formData.append("upload_preset", CLOUDIARY_UPLOAD_PRESET)
axios({
url: CLOUDINARY_URL,
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
data: formData
}).then(function(res){
callback(new Meteor.Error(400, "Error"), res);
}).catch(function(err){
console.log(err);
})
console.log(file);
}
所以在這裏我做什麼我得到的文件參數,並進入成cloudinary(文件處理API )並嘗試在接收數據時進行回調。我理解回調的概念(sorta)和如何使用它們,但我不確定如何使函數有回調。
addNote(e){
e.preventDefault();
let title = this.refs.title.value;
let subject = this.refs.subject.value;
let description = this.refs.description.value;
let allUrls = [this.refs.imageURL.value].concat(this.state.urls);
let imageURL = allUrls.filter(function(entry) { return entry.trim() != ''; });
let userId = Meteor.userId();
let userEmail = Meteor.user().emails[0].address;
let createdAt = Date.parse(new Date());
let unit = this.refs.unit.value;
let file = this.refs.fileInput.files[0];
if(!Meteor.userId()){
this.setState({
message: "You need to login before you can add a note",
loginMessage: <Link to="/login">Login</Link>
})
throw new Meteor.Error(400, "User is not signed in.")
}
if(title && subject && description && unit){
if(imageURL || file){
let noteInfo = { title, subject, description, imageURL, userId, userEmail, createdAt, unit };
this.uploadToCloudinary(file, (err, res) => {
console.log(res)
});
//need to make a callback for this^^^^ (ln 52)
Meteor.call("notes.insert", noteInfo, (err, res) => {
if(err){
this.setState({message: err.reason});
console.log(err)
}else{
this.props.history.push("/")
}
})
}else {
this.setState({ message: "You must fill in all the blanks. " })
}
}
}
這裏是我試圖調用函數,並希望得到錯誤/響應。所以我的問題是如何在反應組件中進行回調?我不斷收到callback is not defined
的錯誤。