首页 > 解决方案 > 如何覆盖文件对象值?

问题描述

我有一个函数,它基本上从数组中获取一个文件对象,并通过一些调整来复制它:

i是数组索引

  duplicate(i) {
    const arr = [...this.state.files];
    console.log(arr[i].color) //red

    let name = arr[i].name.slice(0, -4);
    name = `${name}-${Math.floor(Math.random() * 1000) + 1}.png`;

    const newFile = new File([""],name)
    const index = i + 1;

    arr.splice(index, 0, newFile)
    arr[i+1].id = Math.random().toString(32);
    arr[i+1].color = arr[i].color //set the color to red
    arr[i+1].preview = arr[i].preview;
    console.log(arr[i+1]) //color in arr is now black (the default color)
    this.setState({
      files: arr
    })
  }

发生的事情是文件对象被重新创建到数组中,然后我成功地给它一个新名称、一个 id 和一个预览值。

我尝试分配颜色值,但这失败了,因为颜色已经是对象中的一个值。

如何覆盖现有值?

标签: javascriptarraysreactjs

解决方案


构造File函数允许您在创建它时提供可选属性。尝试将所有属性放在那里,而不是稍后更改它们。

const newFile = new File([""], name, {
    id: Math.random().toString(32),
    color: arr[i].color,
    preview: arr[i].preview
});

推荐阅读