点击preview_footer按钮上传图片时出现uploadTask.on is not a function错误
解决Preview.js中
uploadTask.on is not a function错误 错误根源
Firebase V9采用模块化API设计,uploadString返回的是Promise对象,而非V8版本中带有on方法的上传任务实例,因此调用uploadTask.on会触发类型错误。同时你的代码里还有几处Firebase API使用错误,一并修正如下:
修正后的完整代码
import React, { useEffect } from 'react'; import './Preview.css'; import { useDispatch, useSelector } from 'react-redux'; import { resetCameraImage, selectCameraImage } from './features/cameraSlice'; import { useNavigate } from 'react-router-dom'; import CloseIcon from '@mui/icons-material/Close'; import TextFieldsIcon from '@mui/icons-material/TextFields'; import CreateIcon from '@mui/icons-material/Create'; import NoteIcon from '@mui/icons-material/Note'; import MusicNoteIcon from '@mui/icons-material/MusicNote'; import AttachFileIcon from '@mui/icons-material/AttachFile'; import CropIcon from '@mui/icons-material/Crop'; import TimerIcon from '@mui/icons-material/Timer'; import SendIcon from '@mui/icons-material/Send'; import { v4 as uuidv4 } from 'uuid'; import { db, storage } from './firebase'; import { uploadString, ref, getDownloadURL } from 'firebase/storage'; import { collection, addDoc, serverTimestamp } from 'firebase/firestore'; function Preview() { const cameraImage = useSelector(selectCameraImage); const navigate = useNavigate() ; const dispatch=useDispatch(); useEffect (() => { if(!cameraImage){ navigate("/", { replace: true }) } }, [cameraImage, navigate]); const closePreview = () => { dispatch(resetCameraImage()); } const sendPost = async () => { try { const id = uuidv4(); const storageRef = ref(storage, `posts/${id}`); // 上传图片,用async/await处理异步操作 await uploadString(storageRef, cameraImage, "data_url"); // 获取图片下载URL const url = await getDownloadURL(storageRef); // 将数据写入Firestore await addDoc(collection(db, 'posts'), { imageUrl: url, username: 'ABC', read: false, timeStamp: serverTimestamp(), }); navigate('/chats', { replace: true }); } catch (error) { console.error('上传或保存失败:', error); } } return ( <div className='preview'> <CloseIcon onClick={closePreview} className='preview_close'/> <div className='preview_toolbarRight'> <TextFieldsIcon/> <CreateIcon/> <NoteIcon/> <MusicNoteIcon/> <AttachFileIcon/> <CropIcon/> <TimerIcon/> </div> <img src={cameraImage} alt='' /> <div onClick={sendPost} className='preview_footer'> <h2> Send To</h2> <SendIcon fontSize='small' className='preview_sendIcon'/> </div> </div> ); } export default Preview;
核心修正说明
- 移除
uploadTask.on回调:改用async/await处理uploadString的异步流程,适配V9模块化API - 修正Firestore写入逻辑:V9中添加文档必须使用
addDoc方法,替代旧版collection.add语法 - 简化下载URL获取:直接调用
getDownloadURL(storageRef)即可,V9中不再支持链式调用ref().child()这类实例方法 - 修复拼写错误:将
closPreview改为closePreview,避免函数调用失败
内容的提问来源于stack exchange,提问作者Shivangi Bose
相关产品推荐
相关产品推荐

