我正在尝试在我的应用程序上实现 Dropzone,但如果照片作为多重输入拖放,我无法预览照片。如果我一个接一个地添加它们,它可以正常工作,但如果我选择多个,则只会渲染第一个。
这是我的 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
元素具有键。 - 我会为整个组件使用文件读取器的实例,而不是在每次调用
onDropGeneral
方法时创建一个新实例。您可以在componentDidMount
中为"load"事件附加事件侦听器,并在componentWillUnmount
中删除该侦听器。至少,最好在调用reader.readAsDataURL
之前附加该事件侦听器。