有人可以帮我解决这个问题吗?我无法将“预览”设置为“imagePreview”。它仍然显示空数组 []
"use client";
import Image from "next/image";
import React, { useState } from "react";
const FileUploder = () => {
const [imagePreviews, setImagePreviews] = useState([]);
function handleFileUpload(e) {
const files = e.target.files;
console.log(files);
const previews = Array.from(files).map((file) => URL.createObjectURL(file));
setImagePreviews(previews);
console.log(imagePreviews);
}
我在我的 nextjs 应用程序之一中使用了文件上传组件。您可以参考以下代码:-
"use client";
import Image from "next/image";
import React, { useState } from "react";
const FileUploder = () => {
const [imagePreviews, setImagePreviews] = useState([]);
function handleFileUpload(e) {
const files = e.target.files;
console.log(files);
// Create an empty array to store the previews
const previews = [];
// Loop through each file and create an object URL for it
for (const file of files) {
previews.push(URL.createObjectURL(file));
}
// Update the imagePreviews state with the new previews array
setImagePreviews(previews);
console.log(imagePreviews); // This should now show the object URLs
}
return (
<div>
<input type="file" multiple onChange={handleFileUpload} />
{imagePreviews.length > 0 && (
<div>
{imagePreviews.map((preview) => (
<Image key={preview} src={preview} alt="" width={200} height={200} /> // Assuming you want to display the images
))}
</div>
)}
</div>
);
};
export default FileUploder;
让我知道这是否有效。
由于
useState
钩子的异步特性,状态会在一段时间后更新。
setImagePreviews(previews);
console.log(imagePreviews);
因此你会在console.log()中发现未更新的空数组。您可以阅读更多相关内容 这里