【问题标题】:How to append files in another object ReactJS?如何在另一个对象 ReactJS 中附加文件?
【发布时间】:2022-01-12 09:29:01
【问题描述】:

我有一个文件数组,用于稍后将它们附加到表单数据中,但首先我需要压缩它们并附加到已压缩文件的新数组中。 我无法在循环中将文件附加到新数组

我做了什么尝试:

const [compressedImages, setCompressedImages] = useState([]);

循环中:

setCompressedImages(...compressed) //it doesn't seem to work

再试一次: (循环中)

compressedImages = [...compressed] //doesn't work

compressedImages.push(compressed) //doesn't work

为什么传播运算符在这种情况下不起作用?

我有什么

<input
       type="file"
       multiple
       onChange={e => selectImages(e)}
  />

函数选择图像:

const [images , setImages] = useState([]);
const selectImages = e => {
        setImages(e.target.files);
    }

然后我需要压缩我的文件并将它们全部附加到另一个数组中。

for (let i = 0; i<images.length; i++){
            let compressed = await imageCompression(images[i], options)
            images = [...compressed]
            //at the end of the loop I must have exactly the same array as 'images' 
            //but with already processed files
        }

【问题讨论】:

    标签: javascript arrays reactjs loops


    【解决方案1】:

    要将元素添加到数组状态,您应该根据当前状态创建一个新数组并将新元素添加到其中,然后将新数组设置为状态:

    const [myState, setMyState] = useState([]);
    // Add an element to state(long way)
    myState.push('element');
    setMyState(myState);
    // Add an element to state(short way)
    setMyState([...myState, 'element']);
    

    【讨论】:

    • Uncaught (in promise) TypeError: compressed is not iterable
    • 尝试重新检查你的变量名@Grandeamore
    • compressedImages 使用 setter setCompressedImages 设置。我猜你的意思是:如果我有: let compressed = await imageCompression(e,options); setCompressedImages([...compressed]) 而不是建议:setCompressedImages([...compressedImages])。但无论如何它是不可迭代的
    • compressed 是您要添加到compressedImages 的元素吗?如果是这样,你可以setCompressedImages([...compressedImages, compressed])@Grandeamore
    • 它正在工作!谢谢!我在循环中使用 state.push 并将 setter 放在循环之后。
    猜你喜欢
    • 1970-01-01
    • 2019-05-13
    • 2016-01-31
    • 2010-11-29
    • 1970-01-01
    • 2022-11-28
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    相关资源
    最近更新 更多