简体   繁体   中英

Deleting object from state array

I am in the middle of implementing delete functionality to an image uploader. My error message is Cannot read property 'id' of undefined . I don't think I am assigning an id correctly and my approach is wrong to the task at hand.

  • Tried passing the object into the function and using JavaScripts delete API to delete the specific file. Not best practice to mutate the state directly rather to copy the state, modify then paste the new state.
  • Tried using the name as the indentifier but does not work. I am recommended to delete by an id or key.
import * as React from "react"
import Dropzone, { DropFilesEventHandler } from "react-dropzone"
import FaIcon from "components/FaIcon"
import { PrimaryButton } from "components/Buttons"

interface ImageFile extends File {
  preview?: string
  id: any
}

class ImageUpload extends React.Component {
  state = {
    files: []
  }

  onDrop: DropFilesEventHandler = (files: ImageFile[]) => {
    files.map(file => Object.assign(file, {
      preview: URL.createObjectURL(file)
    }))
    this.setState({ files: [...this.state.files, ...files] })
  }

  deleteImage = (file: ImageFile, index: number) => {
    console.log(file, index)
    // this.setState({
    //   files: this.state.files.filter(file => file.name !== file),
    // });
  }

  render() {
    const files = this.state.files.map((file: ImageFile, index: number) => (
      console.log(file),
      (
        <div key={index}>
          <div>
            <img src={file.preview} />
            <div onClick={() => this.deleteImage(file, index)}>
              <FaIcon icon="plus" />
            </div>
          </div>
        </div>
      )
    ))

    return (
      <div>
        <div>
          <h2>Upload Images</h2>
        </div>
        <form>
          <div>
            {files}
            <Dropzone onDrop={this.onDrop} accept="image/*">
              <FaIcon icon="plus"/>
            </Dropzone>
          </div>
          <div>
            <label>Category</label>
            <div>
              <input
                type="text"
                placeholder={"please enter / select..."}
                value={this.state.categoryInput}
                onChange={(e) => this.categoryInputValue(e)}
              />
            </div>
            <PrimaryButton>Upload</PrimaryButton>
          </div>
        </form>
      </div >
    )
  }
}

export default ImageUpload

I expect the file to be removed from the array. Actual result is nothing happens and error message appears.

deleteImage = (file_id) => {
  const { files } = this.state;
  this.setState({
    files: files.filter(file => file.id !== file_id),
  });
}

You should write this as you are passing file id into the deleteImage function.

You could remove the object with an index value

deleteImage = (file, index) => {

    const myNewFiles = [...this.state.files]; // copy of Original State
    myNewFiles.splice(index, 1);
    this.setState({
      files: myNewFiles
    });
  };

and i've also made a sandbox example

https://codesandbox.io/embed/0krqwkokw

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