[英]React setState with Filelist using forEach
當用戶拖放多個文件時,我想將setState
與 forEach 一起使用。 假設我已經有類似的東西:
class FileCreate extends Component {
constructor(props) {
super(props)
this.state = {
files: [],
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(files) {
if (files && files != undefined) {
Array.from(files).forEach((file, index) => {
this.setState({ files: [...this.state.files, file] })
})
} else {
console.log('file error')
}
}
}
當console.log(this.state.files)
使用setState()
和forEach()
方法時,它只返回 Filelist 中第二個文件的結果?
forEach
是不必要的(並且有問題)。
如果 files 是一個數組,則只需:
if (files && files != undefined) {
this.setState({files:[ ...this.state.files, ...files]});
} else {
console.log('file error')
}
這可能是由於setState
異步行為。 forEach
不是異步的,這是導致問題的原因。 您可以嘗試以下操作:
handleChange(files) {
if (files && files != undefined) {
let newFiles = [];
Array.from(files).forEach((file) => {
// Use this approach if you want to change file object else forEach is redundant
newFiles.push(file);
});
this.setState({ files: [...this.state.files, ...newFiles] })
} else {
console.log('file error')
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.