简体   繁体   English

从状态数组中删除对象

[英]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 . 我的错误消息是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. 我认为我没有正确分配ID,而我的方法对手头的任务是错误的。

  • Tried passing the object into the function and using JavaScripts delete API to delete the specific file. 尝试将对象传递到函数中,并使用JavaScript的delete API删除特定文件。 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. 建议通过ID或密钥删除。
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. 在将文件ID传递到deleteImage函数时,应该编写此代码。

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 https://codesandbox.io/embed/0krqwkokw

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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