简体   繁体   English

提交处理程序,React Axios:在同一个处理程序中发布和获取

[英]Submit handler, React Axios: Post and Get in same handler

I am trying to create a web app that uploads file and attached the current user to the file model as a foreign key.我正在尝试创建一个 web 应用程序,该应用程序上传文件并将当前用户附加到文件 model 作为外键。 For some reason the get request is being wiped, but it does initially get the needed information.由于某种原因,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))
  };

The 1st console is returning the user information but the 2nd console returns null.第一个控制台返回用户信息,但第二个控制台返回 null。 Any help will be really appreciated.任何帮助将不胜感激。

Your then statement after the original get ends on line 11, and the rest of your code is outside of that.原始get之后的then语句在第 11 行结束,并且代码的 rest 不在此范围内。

With asynchronous code, the code outside of the then block will continue running while it's waiting for a response, so this.state.creator will not have been set yet.使用异步代码, then块之外的代码将在等待响应时继续运行,因此尚未设置this.state.creator Then it will return to the code inside the then block once the promise resolves.然后,一旦 promise 解析,它将返回到then块内的代码。

You need to move all of the second block of code inside the intial then block so it is only executed once a response to the original get request has returned:您需要将所有第二个代码块移动到 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM