[英]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.