简体   繁体   English

React JSX JSZip-var作用域不正确

[英]React JSX JSZip - var scope incorrect

I am trying to open a zip file, grab certain elements from it, push them into an array, and use that array to render a list of components in react. 我正在尝试打开一个zip文件,从中获取某些元素,将它们推入数组,然后使用该数组来呈现react中的组件列表。 The problem I'm having is that anything I do to nameArray inside of this for loop isn't recognized outside of it. 我遇到的问题是我在此for循环内对nameArray所做的任何操作都无法识别。

isUploadPressed(props) {
if(props === true) {
  let zip = new JSZip(); 

  JSZip.loadAsync(this.state.zipFile).then(function (zip) {
    var listOfFiles;

    for (let zipEntry of Array.from(zip)) {
      var nameArray = new Array;
      nameArray.push(zipEntry.split('/').pop());
    }
    alert("NameArray: " + nameArray.pop());
    nameArray.map((element) => listOfFiles.push(<li><File fileName={element}/></li>)) 
    return listOfFiles;
  });

}

} }

Unhandled Rejection (TypeError): Cannot read property 'pop' of undefined 未处理的拒绝(TypeError):无法读取未定义的属性“ pop”

you should declare the var nameArray = new Array; 您应该声明var nameArray = new Array; outside of the for loop so you can call the variable. for循环之外,因此您可以调用变量。

isUploadPressed(props) {
if(props === true) {
  let zip = new JSZip(); 

  JSZip.loadAsync(this.state.zipFile).then(function (zip) {
    var listOfFiles;
    var nameArray = new Array;

    for (let zipEntry of Array.from(zip)) {
      nameArray.push(zipEntry.split('/').pop());
    }

    alert("NameArray: " + nameArray.pop()); // Now you should be able to call nameArray properly
    nameArray.map((element) => listOfFiles.push(<li><File fileName={element}/></li>)) 
    return listOfFiles;
  });

}

I suggest you to read and understand more about scope here: What is the scope of variables in JavaScript? 我建议您在这里阅读和了解更多有关范围的知识: JavaScript中变量的范围是什么?

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

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