Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

reactjs - How to solve setState not updating in React?

Here I'm trying to select multiple files and upload them at one click.When I select single file and upload then it render correctly. But when I upload more than one file ,the last one is not displaying.But it gets stored in the array.It's like always on step behind.Below 2 function


  handleClick = (fileUploader) => {
    fileUploader.current.click();
    // this.setState({ selectedFile: event.target.files[0] });
  };

  handleChangeFile = (event) => {
    for (var i = 0; i < event.target.files.length; i++) {
      const fileUploaded = event.target.files[i];
      this.setState({ uploadedFileName: fileUploaded.name });
      this.setState({ uploadedFileType: fileUploaded.type });

      this.setState({
        selectedFiles: this.state.selectedFiles.concat(fileUploaded)
      });
    }
    console.log(this.state.selectedFiles);
  };

Inside render

const decription = this.state.selectedFiles.map((item) => {item.name}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I found a way to solve this.

handleChangeFile = (event) => {
    var temp = [];
    for (var i = 0; i < event.target.files.length; i++) {
      temp.push(event.target.files[i]);
    }
    this.setState({
      selectedFiles: this.state.selectedFiles.concat(temp)
    });
 
  };

We must create a temp array. This is easy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...