Реагировать на состояние загрузки - PullRequest
0 голосов
/ 05 марта 2020

этот код загружает файлы правильно и удаляет их также правильно, но почему-то функция my files.map в рендере ничего не показывает из состояния после удаления одного файла , хотя остальные файлы там, как я вижу в моем console.logs.

Есть идеи, что я делаю не так?

import React, { Component } from "react";
import * as RB from "react-bootstrap";
import Button from "components/Button/Button";
import HighlightOffIcon from "@material-ui/icons/HighlightOff";

class uploadMob extends Component {
  constructor(props) {
    super(props);
    this.state = {
      files: []
    };
  }
  componentDidUpdate(prevProps) {
    if (this.props.files !== prevProps.files) {
      this.setState({ files: [] });
    }
  }

  onFilesAdded = e => {
    if (typeof e.target.files[0] === "undefined") return;
    const file = e.target.files[0];
    if (file.size / 1000 >= 5120) {
      alert(
        "Fehler: Maximale Dateigröße ist 5MB. Bitte reduziere deine Dateiengröße."
      );
      return;
    }
    this.uploadFiles(file);
    this.updateState(file);
  };

  updateState = file => {
    const array = this.state.files;
    array.push(file);
    this.setState({
      files: array
    });
  };

  uploadFiles = async file => {
    const { pdfUploadToState } = this.props;
    pdfUploadToState(file);
  };

  triggerInput = () => {
    document.getElementById("files").click();
  };

  deleteFile = e => {
    //Remove item from files array by click
    const indexItem = e.currentTarget.dataset.index;
    const array = [...this.state.files];
    const newFiles = array.filter(
      (item, index) => index !== parseInt(indexItem)
    );
    console.log("indexITem", indexItem);
    console.log("stateFiles", array);
    console.log("newFiles", newFiles);
    this.setState({
      files: newFiles
    });
    this.setFiles(newFiles);
    console.log("NEWstateFiles", this.state.files);
  };

  setFiles = files => {
    const { setFiles } = this.props;
    setFiles(files);
  };

  render() {
    const files = this.state.files;
    return (
      <RB.Col className="upload-btn-wrapper-col">
        <div className="upload-btn-wrapper">
          <div className="Files">
            {files.map((file, key) => {
              console.log("NEWNEWNEWstateFiles", files);
              return (
                <div
                  key={key}
                  className="Row"
                  onClick={e => {
                    this.deleteFile(e);
                  }}
                  data-index={key}
                >
                  <span className="Filename">
                    {file.name} <HighlightOffIcon color="primary" />
                  </span>
                </div>
              );
            })}
          </div>
          <Button size="sm" variant="light" onClick={this.triggerInput}>
            Dateien hochladen
          </Button>
          <input
            type="file"
            accept="application/pdf,image/jpeg,image/png"
            hidden
            name="files"
            id="files"
            onChange={e => {
              this.onFilesAdded(e);
            }}
          />
        </div>
      </RB.Col>
    );
  }
}

export default uploadMob;

Буду очень признателен за любую помощь. Я застрял с этим. Спасибо!

Карлес

...