简体   繁体   English

用回调和传递道具来反应setState

[英]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. 我有一个文件上传组件(我正在React中工作),它会通过点击处理程序触发文件上传。 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. 因此,当调用文件处理程序函数时,我的加载状态设置为true。 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. 因此,我四处搜索,发现可以将回调传递给setState,该回调将在状态更改和组件重新呈现后触发。 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} -此日志:文件列表{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. 顺便说一句,事件是在另一个函数中处理的,并且事件目标(文件)正在传递给handleFiles函数,问题似乎出在将文件传递给回调函数。

Thanks 谢谢

I would recommend using a promise to handle async requests; 我建议使用Promise处理异步请求; a library like axios works very well. 像axios这样的库效果很好。 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
      });   
   });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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