我有一个文件列表,我想为其找到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>
}

最佳答案

// 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>
  }
}

关于javascript - 新的FileReader(); react 。遍历项目时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57677785/

10-09 10:15