首页 > 解决方案 > 使用 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()

标签: javascriptreactjs

解决方案


forEach是不必要的(并且有问题)。

如果 files 是一个数组,那么只需:

    if (files && files != undefined) {
      this.setState({files:[ ...this.state.files, ...files]});
    } else {
      console.log('file error')
    }

推荐阅读