【问题标题】:Submit handler, React Axios: Post and Get in same handler提交处理程序,React Axios:在同一个处理程序中发布和获取
【发布时间】:2022-01-02 09:48:05
【问题描述】:

我正在尝试创建一个上传文件并将当前用户作为外键附加到文件模型的 Web 应用程序。出于某种原因,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。任何帮助将不胜感激。

【问题讨论】:

    标签: javascript reactjs react-native api axios


    【解决方案1】:

    您在原始 get 之后的 then 语句在第 11 行结束,您的其余代码不在此范围内。

    使用异步代码,then 块之外的代码将在等待响应时继续运行,因此尚未设置 this.state.creator。然后,一旦 promise 解决,它将返回到 then 块内的代码。

    您需要将所有第二个代码块移动到初始 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));
        });
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-08
      • 2018-06-12
      • 2015-02-18
      • 2023-04-04
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 2016-03-19
      相关资源
      最近更新 更多