Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在filereader onload回调中访问局部变量_Javascript_Reactjs_File Upload_Callback - Fatal编程技术网

Javascript 如何在filereader onload回调中访问局部变量

Javascript 如何在filereader onload回调中访问局部变量,javascript,reactjs,file-upload,callback,Javascript,Reactjs,File Upload,Callback,我正在React中执行文件上载操作,我需要读取从用户上载的文件,并根据此文件进行一些状态更改。我现在拥有的如下所示,我需要访问onload回调中的变量startInt,但这里仍然没有使用IIFE定义它 const file = document.getElementById("fileUpload").files[0]; if (file) { const reader = new FileReader(); reader.readAsText(file, "UTF-8"); re

我正在React中执行文件上载操作,我需要读取从用户上载的文件,并根据此文件进行一些状态更改。我现在拥有的如下所示,我需要访问
onload
回调中的变量
startInt
,但这里仍然没有使用IIFE定义它

const file = document.getElementById("fileUpload").files[0];
if (file) {
  const reader = new FileReader();
  reader.readAsText(file, "UTF-8");

  reader.onload = ((theFile) => {
    const form = document.getElementById('fileUploadForm');
    const start = datetimeToISO(form.Start.value);
    const startInt = new Date(start).getTime();

    return (e) => {
      console.log(e.target.result);
      //startInt is not defined here
    }
  })(file);
}
如果有帮助,我会遵循以下指南:

如果你能指出我的错误那就太好了。非常感谢您可以访问本地var(但不能像这样访问class const.state.*或this.props.*)。 所以你需要这样的东西:

    var file = document.getElementById('inputID').files[0]
    var Images = this.props.motherState.Images // Images is array 
    var reader = new FileReader();
    reader.readAsDataURL(file); //

    reader.onload = function () {
        //console.log(reader.result);
        if (file.type.match(/image.*/))           
            Images.push(reader.result) // its ok
        // but  this.props.motherState.Images.push(reader.result)
        // return error like this:
        // Images not define in this.props.motherState.Images
    };



    reader.onerror = function (error) {
        //console.log('Error: ', error);
    };

我不确定它是否会对您有所帮助,但这里有另一个示例,但其中定义了
startInt