代码之家  ›  专栏  ›  技术社区  ›  Hysii

以同步方式集成两个反应函数

  •  0
  • Hysii  · 技术社区  · 6 年前

    我有下面的反应代码。我希望以同步方式将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);
          });
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Mahima    6 年前
    handleUpdate = event => {
      this.setState({
       selectedFile: event.target.files[0]
      }, ()=>this.handleUpload())
    }
    

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