我希望在提交表單時,選擇的文本輸入和檔案應分別上傳到 firestore 集合和 firebase 存盤。我不明白為什么它給我錯誤。
這是我的表格:
<form onSubmit={postSubmitHandler}>
<input type="text" ref={postTextRef}/>
<input type="file"/>
<button type="submit">Upload</button>
</form>
這是我的處理程式函式:
function postSubmitHandler(e) {
e.preventDefault();
const file = e.target .files[0];
console.log(file)
if (!file) return;
const sotrageRef = ref(storage, `posts/${file.name}`);
const uploadTask = uploadBytesResumable(sotrageRef, file);
uploadTask.on(
"state_changed",
(snapshot) => {
const prog = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(prog);
},
(error) => console.log(error),
() => {
getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) => {
console.log("File available at", downloadURL);
firestore.collection('posts').doc(currentUser.uid).set({
imageURL: downloadURL,
caption: postTextRef.current.value,
postedAt: new Date(),
likes: 0
})
});
}
);
}
我得到的錯誤是:
TypeError: Cannot read properties of undefined (reading '0')
47 |
48 | function postSubmitHandler(e) {
49 | e.preventDefault();
> 50 | const file = e.target.files[0];
51 | ^
請幫我糾正這個錯誤,或者如果有其他好的方法,請告訴我。
uj5u.com熱心網友回復:
由于您postSubmitHandler正在回應form提交的內容,因此它e.target指向表單元素 - 而不是input檔案所在的位置。
快速修復:
const input = e.target.querySelector("input[type='file']");
const file = input.files[0];
此處的第一行從您的表單 ( e.target) 中選擇正確的輸入,然后用于訪問files用戶選擇的輸入。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/367127.html
標籤:反应 火力基地 谷歌云firestore 火力存储
