【问题标题】:Add attachments to attachments array将附件添加到附件数组
【发布时间】:2019-05-28 08:25:26
【问题描述】:

我有以下功能,可将<input type="file" multiple /> 中的附件添加到父母的状态。

在用户想要添加另一个附件之前效果很好,新附件会覆盖现有附件,如何将新附件添加到现有附件数组中?

handleAddAttachments = fileList => {
  this.props.handleChange('attachments', Array.from(fileList));
};

我试过了,但它似乎不起作用。

handleAddAttachments = fileList => {
  const { attachments } = this.props.ticket;
  this.props.handleChange('attachments', [...attachments, fileList]);
};

handleChange函数:

makeHandleChange = (pageName, change) => {
  this.setState({
    ticket: { ...this.state.ticket, [pageName]: change },
  });
};

【问题讨论】:

  • 如果你console.log([...attachments, fileList]) 看到预期的结果了吗?
  • @sigmus,不,假设我先添加了 3 个附件,然后添加了第 4 个附件,我看到的是 [{"0": {},"1": {},"2": {}}{"0": {}}],而不是我希望看到的 [{},{},{},{}]

标签: javascript


【解决方案1】:

在您的第二个版本中,您缺少 Array.from() 部分。来自 fileInput 的更改不是直接的数组,因此扩展运算符不起作用。

这应该可以解决问题:

handleAddAttachments = fileList => {
  const { attachments } = this.props.ticket;
  this.props.handleChange('attachments', [...attachments, ...Array.from(fileList)]);
};

关于为什么它不是数组的更多信息,你可以在这里找到一些信息:Why isn't the FileList object an array?

感谢@sigmus,我将缺少的传播添加到Array.from()

【讨论】:

  • 我也试过了,结果首先是[[{},{},{},{}]]而不是[{},{},{},{}],然后当我添加新附件时结果是:[[{},{},{},{}],[{}]]而不是[{},{},{},{},{}]
  • 如果你也传播Array.from,比如[...attachments, ...Array.from(fileList)]?
  • @NicolasGehlert 请更新您的问题,以便我接受
猜你喜欢
  • 2013-09-18
  • 2012-05-28
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 2016-08-29
  • 2018-03-19
  • 2017-04-08
  • 1970-01-01
相关资源
最近更新 更多