javascript - 使用 forEach 将 setState 与 Filelist 反应
问题描述
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')
}
}
}
当使用with方法console.log(this.state.files)
有什么问题时,它只返回来自 Filelist 的第二个文件的结果?setState()
forEach()
解决方案
这forEach
是不必要的(并且有问题)。
如果 files 是一个数组,那么只需:
if (files && files != undefined) {
this.setState({files:[ ...this.state.files, ...files]});
} else {
console.log('file error')
}
推荐阅读
- python-3.x - Python中列表列表的数据标准化
- node.js - 没有用户注册时如何保护我的 api 端点
- javascript - 使用 javascript 检查 iframe 中是否存在特定文本
- ios - Firebase Crashlytics 上的“上传缺少的 dSYM 以查看来自 1 个版本的崩溃”
- spring - Spring @PreAuthorize 抛出 LazyInitializationException 从 Hibernate 访问惰性数据
- javascript - 不隐藏我的 API 密钥和秘密有什么风险?
- java - Docker:Java+Python 应用程序的基础镜像
- python - Python 发送简单邮件
- google-cloud-platform - 损坏的 DAG:应用程序的错误响应:429
- go - 如何更改列表中的元素?