繁体   English   中英

使用 forEach 将 setState 与 Filelist 反应

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM