简体   繁体   中英

How to access a local variable in filereader onload callback

I am doing a file upload operation in React, and I need to read the file uploaded from the user and do some state changes according to this file. What I have right now is shown below and I need to need to access the variable startInt within the onload callback, but it is still not defined here using the 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);
}

I followed this guide if it helps: https://stackoverflow.com/a/16937439/6366329

If you could point out my mistake that would be great. Many thanks in advance

you can access local var (but not class const like this.state.* or this .props.*). so something like this you need:

    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);
    };

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