React TypeScript中无法向FormData添加文件的技术问题
解决React+TypeScript中FormData添加File报错的问题
报错原因
你的imageFile状态未指定类型,TypeScript默认推断其为unknown,而FormData.append()的第二个参数要求是Blob | string | undefined,类型不匹配导致报错。
解决方案
为useState指定明确类型
将状态声明改为File | undefined类型,明确表示它要么是File对象,要么未定义:const [imageFile, setImageFile] = React.useState<File | undefined>();添加非空校验(可选但推荐)
在提交时先判断imageFile是否存在,避免空值传递:const handleOnSubmit = (values: Picture) => { if (!imageFile) return; const formData = new FormData(); formData.append("formFile", imageFile); productImageMutation({ data: formData }); };
完整修正代码
const [imageFile, setImageFile] = React.useState<File | undefined>(); const [productImageMutation, productImageMutationResult] = useAddProductImageMutation(); const handleUploadClick = (e: React.ChangeEvent<HTMLInputElement>) => { const file = e.target.files?.[0]; if (file) setImageFile(file); }; const handleOnSubmit = (values: Picture) => { if (!imageFile) return; const formData = new FormData(); formData.append("formFile", imageFile); productImageMutation({ data: formData }); };
另外,建议把handleUploadClick的参数类型从any改为React.ChangeEvent<HTMLInputElement>,让类型检查更严谨。
内容的提问来源于stack exchange,提问作者Mehran Ayub
相关产品推荐
相关产品推荐

