使用 react-dropzone 预览多个拖放

Preview multiple drop using react-dropzone

我正在尝试在我的应用程序上实施 Dropzone,但如果照片作为多重输入放置,我将无法预览。如果我一个一个地添加它们,它工作正常,但如果我 select 多个,只有第一个被渲染。

这是我的 onDrop 函数

onDropGeneral = (currentGeneralPhoto) => {
 let index;
 for (index = 0; index < currentGeneralPhoto.length; ++index) {
  const file = currentGeneralPhoto[index];
  this.setState({
    previewGeneralPhotos: this.state.previewGeneralPhotos.concat(file)
  });
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = (event) => {
    console.log('URL: ', event.target.result);
    this.setState({
      generalPhotos: this.state.generalPhotos.concat([{ base64: event.target.result }])
    });
  };
 }
}

这是我的渲染方法:

<h2>Dropped files</h2>
{this.state.previewGeneralPhotos.length > 0 ? <div>
  <h2>Preview {this.state.previewGeneralPhotos.length} files...</h2>
  <div>{this.state.previewGeneralPhotos.map((file) => <img src={file.preview} alt="preview failed" />)}</div>
 </div> : null}
 <h2> Upload {this.state.generalPhotos.length} Files </h2>

上传计数显示数组的正确大小,但预览计数仅计算第一张丢弃的照片

所以你的问题是因为 setState 可以是异步的。您应该在 onDropGeneral 函数中使用 setState 的回调函数:

this.setState(({ previewGeneralPhotos }) => ({
  previewGeneralPhotos: previewGeneralPhotos.concat(file)
}))

这将确保您不会意外地覆盖 previewGeneralPhotos 的先前值,并且您实际上会按照您的意愿添加到现有数组中。

其他一些建议:

  • 确保您的 img 元素有一个键。
  • 我会为整个组件使用文件 reader 的实例,而不是每次调用 onDropGeneral 方法时都创建一个新实例。您可以为 componentDidMount 中的 'load' 事件附加事件侦听器,并在 componentWillUnmount 中删除该侦听器。至少,最好在 调用 reader.readAsDataURL.
  • 之前附加该事件监听器