英文:
All files in an array not converting to base64 in react js
问题
我有一个名为useBase64的自定义钩子,用于将我的图像转换为Base64。这个钩子接受一个初始值,并返回handleCreateBase64函数和logo(状态片段)。handleCreateBase64将文件转换为base64并将其存储在logo中。我正在发送一个图像文件数组,然后遍历该数组,希望将它们存储在logo中,然后发送到组件。目前的问题是,即使选择多个文件,logo中只能看到一个base64。
useBase64钩子代码如下:
import { useCallback, useState } from "react";
export const useBase64 = (initialValue) => {
const [logo, setLogo] = useState(initialValue);
const handleCreateBase64 = useCallback(async (receivedFile) => {
let file = receivedFile;
if (initialValue instanceof Array) {
file = Object.values(receivedFile);
file.map(async (el) => {
const base64 = await convertToBase64(el);
setLogo([...logo, base64]);
});
}
});
const convertToBase64 = (file) => {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
if (!file) {
console.log("没有图像");
} else {
fileReader.readAsDataURL(file);
fileReader.onload = () => {
resolve(fileReader.result);
};
}
fileReader.onerror = (error) => {
reject(error);
};
});
};
return { handleCreateBase64, logo };
};
结果如下:
如你所见,上面有3个图像被选择,但我只看到了1个base64。我对这方面还比较新,所以如果能提供详细的解释将非常有帮助。
英文:
I have a custom hook called useBase64 where I convert my image to Base64. This hook accepts an initial value and returns handleCreateBase64 function and logo (piece of state). handleCreateBase64 converts the file to base64 and stores it in logo. I am sending an array of images as File and then mapping through that array and I want to store it in logo and then send it to that component. right now the problem is that in the logo I can only see 1 base64 even if I select multiple files.
useBase64 hook: -
import { useCallback, useState } from "react";
export const useBase64 = (initialValue) => {
const [logo, setLogo] = useState(initialValue)
const handleCreateBase64 = useCallback(async (receivedFile) => {
let file = receivedFile;
if(initialValue instanceof Array) {
file = Object.values(receivedFile)
file.map(async el => {
const base64 = await convertToBase64(el)
setLogo([...logo, base64])
})
}
});
const convertToBase64 = (file) => {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
if (!file) {
console.log("no image");
} else {
fileReader.readAsDataURL(file);
fileReader.onload = () => {
resolve(fileReader.result);
};
}
fileReader.onerror = (error) => {
reject(error);
};
});
};
return { handleCreateBase64, logo }
}
The result: -
As you can see above that I have 3 images selected but I see only 1 base64. I am quiet new to this so it will be great if full explanation is provided.
答案1
得分: 1
错误使用map和setState
尝试:
const items = await Promise.all(file.map(el => convertToBase64(el)))
setLogo([...logo, ...items])
英文:
Wrong use of map and setState
Try:
const items = await Promise.all(file.map(el => convertToBase64(el)))
setLogo([...logo, ...items])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论