【问题标题】:Add the last item that has been removed from the array添加已从数组中删除的最后一项
【发布时间】:2019-05-17 18:14:08
【问题描述】:

我正在使用“输入类型 = 文件多个”,并且我确实列出了选择的文件,并且可以选择从该列表中删除所选文件。我遇到的问题是我无法添加最后一项我删除了。 假设您要添加已删除的最后一个文件(对于错误,您已删除该文件并且必须添加),我不能这样做,我不能添加该文件

 handleFile = e  => {
    let file = e.target.files   
    for(let i = 0,f; f = file[i]; i ++){
          this.list.push(`${f.name } (${f.size})`)
          this.setState({fileArray: [ ...this.list]})
    }
}
handleRemoveFile = e => {
    this.setState({fileArray: this.state.fileArray.filter(f => {
         return f !== e
        })
    })
     this.list = this.list.filter(f => {
        return f !== e
      })
}

// in render I have
<input id="file-upload" type="file" multiple onChange={this.handleFile}/>
<div>
{this.state.fileArray != undefined&& this.state.fileArray.length>0 ?      
  this.state.fileArray.map((f,index) => {
        return 
    <div style={{display: 'flex'}} key={index}>
           <p> { `${f}`} </p>
           <i className={`fa fa-check ${s.check}`}></i>
      <span onClick={()=>this.handleRemoveFile(f)} 
            style={{marginLeft:'1%'}}>
         <i className={`fa fa-trash-alt ${s.trash}`}></i>
      </span>
    </div>
}) : ''}

【问题讨论】:

  • “我无法添加我删除的最后一项。”。我无法理解。为什么要添加刚刚删除的内容?您想在哪里添加您删除的文件?如果你要删除一些东西,你不应该在任何地方添加它
  • Broda Noel 当我将所有项目删除到列表中但我想添加我因错误而删除的最后一个项目(例如)我不能这样做,我不知道为什么跨度>
  • 你不能这样做,因为你删除了它。你删除它。它消失了。您在 handleRemoveFile 中删除了它。您可能需要在问题中添加更多信息,解释什么是 listfilterArray 数组。您必须更好地解释您要做什么。

标签: reactjs


【解决方案1】:

你说的我不太明白,但是我相信你在点击Remove后过滤文件(隐藏它)时遇到了一些问题,对吧?

问题是您正在过滤比较对象:

this.setState({
  fileArray: this.state.fileArray.filter(f => {
    return f !== e
  })
})

比较fe是个坏主意,主要是这部分代码:

this.list = this.list.filter(f => {
  return f !== e
})

因为e 对象是this.state.fileArray 的一部分,所以e 不存在于list 中。

我推荐两种方法:

  1. 好方法:检查fe 是否具有可用于比较的独特属性。例如:f.id !== e.idf.fileName !== e.fileName
  2. 丑陋的:不是将file对象发送到handleRemove函数,而是发送index。所以,你应该做&lt;span onClick={()=&gt;this.handleRemoveFile(index)},然后:
handleRemoveFile = index => {
    this.setState({fileArray: this.state.fileArray.filter((f, i) => {
         return f=index !== i
        })
    })
     this.list = this.list.filter((f, i) => {
        return index !== i
      })
}

【讨论】:

  • Broda 该项目包含一个字符串 ["Capture7.PNG (10128)", "Capture9.PNG (10276)"] (文件的名称和大小),当我添加时一切正常并删除,问题是我无法添加最后一个被删除的项目。谢谢你的时间,你的帮助!!
猜你喜欢
  • 2013-11-01
  • 1970-01-01
  • 2020-09-22
  • 2015-01-12
  • 2017-05-27
  • 2022-06-25
  • 2021-10-03
  • 2011-03-31
相关资源
最近更新 更多