根据教程,我有完全相同的代码,但我在上传图像时遇到问题。每次我添加图像并单击上传时,我都会收到一条错误消息:
reference.ts:290 Uncaught TypeError: ref._throwIfRoot is not a function
at uploadBytesResumable$1 (reference.ts:290:1)
at uploadBytesResumable (api.ts:164:1)
at uploadFile (AddUser.jsx:22:1)
at AddUser.jsx:49:1
at commitHookEffectListMount (react-dom.development.js:23049:1)
at commitPassiveMountOnFiber (react-dom.development.js:24816:1)
at commitPassiveMountEffects_complete (react-dom.development.js:24781:1)
at commitPassiveMountEffects_begin (react-dom.development.js:24768:1)
at commitPassiveMountEffects (react-dom.development.js:24756:1)
at flushPassiveEffectsImpl (react-dom.development.js:26990:1)
这是我必须添加新用户及其凭据和图像的代码:
import { useEffect, useState } from 'react';
import { doc, setDoc, addDoc, collection, serverTimestamp } from "firebase/firestore";
import { createUserWithEmailAndPassword } from "firebase/auth"
import { db, auth, storage } from '../../firebase';
import { ref, uploadString, getDownloadURL, uploadBytesResumable } from "firebase/storage";
const New = ({ inputs, title }) => {
const [file, setFile] = useState("");
const [data, setData] = useState({});
useEffect(() => {
const uploadFile = () => {
const name = new Date().getTime() + file.name;
const storageRef = (storage, file.name);
const uploadTask = uploadBytesResumable(storageRef, file);
uploadTask.on('state_changed',
(snapshot) => {
const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case 'paused':
console.log('Upload is paused');
break;
case 'running':
console.log('Upload is running');
break;
default: break;
}
},
(error) => {
console.log(error)
},
() => {
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
setData((prev) => ({ ...prev, img: downloadURL }))
});
}
);
}
file && uploadFile();
}, [file])
const handleInput = (e) => {
const id = e.target.id;
const value = e.target.value;
setData({ ...data, [id]: value })
}
const handleAddUser = async (e) => {
e.preventDefault();
try {
const res = await createUserWithEmailAndPassword(auth, data.email, data.password);
// Add a new user in collection
await setDoc(doc(db, "users", res.user.uid), {
...data,
timeStamp: serverTimestamp()
});
} catch (err) {
console.log(err)
}
}
return (
<div className="new">
<Sidebar />
<div className="newContainer">
<Navbar />
<div className="top">
<h1 className="title">{title}</h1>
</div>
<div className="bottom">
<div className="left">
<img src={file ? URL.createObjectURL(file) : "/images/default.jpg"} alt="" />
</div>
<div className="right">
<form onSubmit={handleAddUser}>
<div className="formInput">
<label htmlFor="file">Upload Image</label>
<input type="file" id="file" onChange={(e) => setFile(e.target.files[0])} />
</div>
{inputs.map((input) => (
<div className="formInput" key={input.id}>
<label>{input.label}</label>
<input id={input.id} type={input.type} placeholder={input.placeholder} onChange={handleInput} />
</div>
))}
<button type="submit">SEND</button>
</form>
</div>
</div>
</div>
</div >
)
}
export default New
这就是我的 firebase.js 文件中的内容。我已经初始化了 firebaseConfig 以及将文档上传到集合的所有必要步骤。此外,出于安全目的,我还删除了 firebaseConfig 的所有值。
import {
initializeApp
} from "firebase/app";
import {
getAuth
} from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = getAuth();
export const storage = getStorage(app);
这只是一个错字。
const storageRef = (storage, file.name);
应该是
const storageRef = doc(storage, file.name);
当我们将不同类型的变量传递给
Ref
(Firebase 期望的位置)时,Firebase 会抛出此错误。
正确设置存储参考:
const storageRef = ref(storage, file.name)