简体   繁体   中英

React setState with callback and pass props

I have a file upload component (I'm working in React) that triggers a file upload with an on click handler. I want to display a loading icon whilst the upload is in progress. So I have a loading state that I set to true when the file handler function is called. However the state change is only sometimes rendered before the file upload begins, during which time the browser freezes. So I searched around and found that I can pass a callback to setState which will fire after the state changes and the component re-renders. However in my situation I need to pass the files collected from the event to this callback function... but this is not working. I have tried:

handleFile(files) {

    this.setState({ loading: true }, () => {
         console.log(files)
         // here is where I want to read the files
    })
}

-- This logs: Filelist {length: 0}

handleFile(files) {

    this.setState({ loading: true }, (files) => {
         console.log(files)
         // here is where I want to read the files
    })
}

-- This logs undefined.

Any ideas where I am going wrong with this? BTW the event is handled in another function and the event target (the files) are being passed to the handleFiles function, the problem seems to be passing the files to the callback.

Thanks

I would recommend using a promise to handle async requests; a library like axios works very well. You can then easily manage state changes. For example:

handleFile(url, files) {
   this.setState({
      loading: true
   });

   axios.post(url, {
      data: files
   }).then(response => {
      this.setState({
         loading: false
      });
   })
   .catch(error => {
      console.log('Error posting data.', error);
      this.setState({
         error: true
      });   
   });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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