新的 FileReader(); 反应。迭代项目时

pet*_*gan 1 javascript ecmascript-6 reactjs

我有一个文件列表,我想找到该文件的 base64Data 并将其显示在每个文件的列表中。

我尝试了以下方法,但它不起作用,我想主要原因是reader.onload异步的。

我的代码如下所示

const App = () => {

  // code....
  <ul>
    {Array.from(files).map(file) => {
      const reader = new FileReader();
      let base64Data;
      reader.onload = (event: any) => {
      // I want to use the result here to display 
      // the Base64 data string of file
         console.log(event.target.result);
         base64Data = event.target.result
      };

       reader.readAsDataURL(file);
       return <p>{base64Data}</p>;
    }}
  </ul>
}
Run Code Online (Sandbox Code Playgroud)

Kyr*_*nko 5

// You should load data before rendering. You can't use async functions for render

class App extends React.Component {
  constructor(props) {
    super(props);
    
    this.state = {
      bases: [],
    };
  }
  
  async componentDidMount() {
     const {files} = this.props; // Assuming you get files from props
     
     const promises = files.map((blob) => {            
        return new Promise((res) => {
          const reader = new FileReader();
          reader.readAsDataURL(blob);

          reader.onload = (e) => {
            res(e.target.result);
          }        
        });            
     });
     
     const bases = await Promise.all(promises);
     
     this.setState({bases});
  }
  
  render() {
     const {bases} = this.state;
     
     if (bases.length === 0) return 'No data';
     
     
    <ul>
      {bases.map(base64Data) => {
         return <li>{base64Data}</li>;
      }}
    </ul>
  }
}
Run Code Online (Sandbox Code Playgroud)