簡體   English   中英

從狀態數組中刪除對象

[英]Deleting object from state array

我正在為圖像上傳器實現刪除功能。 我的錯誤消息是Cannot read property 'id' of undefined 我認為我沒有正確分配ID,而我的方法對手頭的任務是錯誤的。

  • 嘗試將對象傳遞到函數中,並使用JavaScript的delete API刪除特定文件。 並非直接更改狀態而是復制狀態,修改然后粘貼新狀態的最佳實踐。
  • 嘗試使用名稱作為標識符,但不起作用。 建議通過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

我希望從陣列中刪除文件。 實際結果是什么也沒有發生,並且出現錯誤信息。

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

在將文件ID傳遞到deleteImage函數時,應該編寫此代碼。

您可以使用索引值刪除對象

deleteImage = (file, index) => {

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

我也做了一個沙盒的例子

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM