简体   繁体   English

映射对象,使用状态以及通过setState中的函数传递值

[英]Mapping objects, and using state, and passing value through a function in setState

I have a react application, where i want to set the state equal to an array of objects, that has been passed through a function. 我有一个React应用程序,在这里我想将状态设置为等于通过函数传递的对象数组。

I have two variables, and is the file extension, and one is the raw data base64 encoded. 我有两个变量,是文件扩展名,一个是原始数据base64编码。

                       this.setState({
                              result: fileItems.map(fileItem => ({
                                "file": this.findFileTypeHandler(fileItem.file.name), 
                                "data": this.getBase64(fileItem.file)
                              }))
                            });
                      }}>

as of right now i just return the value within the two functions, but the issue occurs, when the functions are not asynchronous. 截至目前,我只是返回两个函数中的值,但是当函数不是异步时,就会出现问题。

findFileTypeHandler = file =>{
    return file.split('.').pop();
}

getBase64 = file => {
    //find en måde at gøre den asynkron
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
      console.log(reader.result) 
      this.setState({base64: reader.result})
     return reader.result;
    };
    reader.onerror = function (error) {
      console.log('error is ', error)
    };
  }

the best case scenario, would be to setState, and then assign the value for each map iteration, but how can i pass the data through the functions, and set the state respectivly? 最好的情况是将setState,然后为每个映射迭代分配值,但是我如何才能通过函数传递数据并分别设置状态?

How about use Promise.all to wait all files to be read, then setState the results. 如何使用Promise.all等待所有文件被读取,然后对结果进行setState

Promise.all(
    fileItems.map(fileItem => new Promise((resolve, reject) => {

        //find en måde at gøre den asynkron
        var reader = new FileReader();
        reader.readAsDataURL(fileItem.file);

        reader.onload = () => {
            resolve({
                file: this.findFileTypeHandler(fileItem.file.name),
                data: {
                    base64: reader.result
                }
            });
        };

        reader.onerror = (error) => reject(error);

    }))
)
.then((results) => {

    this.setState({
        result: results
    });

})
.catch((error) => console.log(error));

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

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