[英]Submit handler, React Axios: Post and Get in same handler
我正在嘗試創建一個 web 應用程序,該應用程序上傳文件並將當前用戶附加到文件 model 作為外鍵。 由於某種原因,get 請求正在被擦除,但它最初確實獲得了所需的信息。
handleSubmit = (e) => {
e.preventDefault();
axios.get('http://127.0.0.1:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`,
}
}).then((user) => {
this.state.creator = user.data;
console.log(this.state.creator);
})
console.log(this.state.creator);
let form_data = new FormData();
form_data.append('creator', this.state.creator);
form_data.append('file', this.state.file);
form_data.append('title', this.state.title);
form_data.append('description', this.state.description);
axios.post('http://localhost:8000/core/posts/', form_data, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `JWT ${localStorage.getItem('token')}`,
}
}).then(res => {
console.log(res.data);
}).catch(err => console.log(err))
};
第一個控制台返回用戶信息,但第二個控制台返回 null。 任何幫助將不勝感激。
原始get
之后的then
語句在第 11 行結束,並且代碼的 rest 不在此范圍內。
使用異步代碼, then
塊之外的代碼將在等待響應時繼續運行,因此尚未設置this.state.creator
。 然后,一旦 promise 解析,它將返回到then
塊內的代碼。
您需要將所有第二個代碼塊移動到 intial then
塊中,以便僅在對原始get
請求的響應返回后才執行它:
handleSubmit = e => {
e.preventDefault();
axios
.get('http://127.0.0.1:8000/core/current_user/', {
headers: {
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then(user => {
this.state.creator = user.data;
console.log(this.state.creator);
let form_data = new FormData();
form_data.append('creator', this.state.creator);
form_data.append('file', this.state.file);
form_data.append('title', this.state.title);
form_data.append('description', this.state.description);
axios
.post('http://localhost:8000/core/posts/', form_data, {
headers: {
'Content-Type': 'multipart/form-data',
Authorization: `JWT ${localStorage.getItem('token')}`
}
})
.then(res => {
console.log(res.data);
})
.catch(err => console.log(err));
});
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.