简体   繁体   中英

React setState with Filelist using forEach

I would like to use setState with forEach when user drag and drop with multiple files. 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?

The forEach is unnecessary (and problematic).

If files is an array then just:

    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 . forEach is not asynchronous which is causing the issue. 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')
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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