首页 > 解决方案 > 以同步方式集成两个反应函数

问题描述

我有下面的反应代码。我想以同步的方式将 handleUpdate 集成到 handleUpload 函数中,以便在函数的其余部分执行之前设置状态。我尝试了以下内容,我的编辑以粗体显示,但它似乎是异步执行的,并且在执行之前没有设置状态。谁能告诉我我需要在哪里进行更改以满足我的需求?

handleUpdate = event => {
   this.setState({
     selectedFile: event.target.files[0]
   })
}

handleUpload = () => {
  **this.handleFileChange;**
  var fd = new FormData();
  fd.append('file', this.state.selectedFile, this.state.selectedFile.name);
  fetch('/upload', {method: 'POST', body: fd})
      .then(response => {
          return response.json()})
      .then(result => {
           console.log(result)})
      .catch(function(error) {           
          console.log("ERROR:" + error);
      });
}

标签: reactjsasynchronoussynchronous

解决方案


handleUpdate = event => {
  this.setState({
   selectedFile: event.target.files[0]
  }, ()=>this.handleUpload())
}

您可以在 setState 的回调函数中调用 handleUpload 函数,以确保仅在设置 state.selectedFile 后才调用 handleUpload 函数


推荐阅读