[英]React setState with Filelist using forEach
I would like to use setState
with forEach when user drag and drop with multiple files.当用户拖放多个文件时,我想将setState
与 forEach 一起使用。 Suppose I already have something like :假设我已经有类似的东西:
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')
}
}
}
It only returns a result with second file from Filelist when console.log(this.state.files)
Is there anything wrong with using setState()
with forEach()
method?当console.log(this.state.files)
使用setState()
和forEach()
方法时,它只返回 Filelist 中第二个文件的结果?
The forEach
is unnecessary (and problematic). forEach
是不必要的(并且有问题)。
If files is an array then just:如果 files 是一个数组,则只需:
if (files && files != undefined) {
this.setState({files:[ ...this.state.files, ...files]});
} else {
console.log('file error')
}
That could be due to asynchronous behaviour of setState
.这可能是由于setState
异步行为。 forEach
is not asynchronous which is causing the issue. forEach
不是异步的,这是导致问题的原因。 You can try the following:您可以尝试以下操作:
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.