亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

未捕獲的 FirebaseError:使用無效數據調用函數 DocumentReference

未捕獲的 FirebaseError:使用無效數據調用函數 DocumentReference

繁花如伊 2023-08-05 11:49:53
我目前正在嘗試制作一份調查問卷,讓用戶對圖像進行評分。我想將用戶對圖像評分的值與他們對圖像評分的值一起推送到數據庫。我目前正在將其打印到控制臺日志,但在將其發送到數據庫時遇到問題。它表示單選按鈕的數據不是對象。這是我第一次使用firebase,對JS的經驗很少。function validate() {    var radio = document.getElementsByName("answer");    var checked = false;    for (var i = 0; i < radio.length; i++) {        if (radio[i].checked) {            checked = true;            break;        } else {            checked = false;        }    }    if (checked) {        for (var i = 0; i < radio.length; i++)        {            if (radio[i].checked)            {                selected = (radio[i].value)                window.sessionStorage.setItem("selected", JSON.stringify(selected));                console.log(selected)                changeImage();            }        }             } else {        alert("You must select an answer!")    }}  var currentImage = 0;var imageArray = ["/Users/rate/images/images/practice/sun1.jpg", "/Users/rate/images/images/practice/sun2.jpg", "/Users/rate/images/images/practice/sun3.jpg", "/Users/rate/images/images/practice/sun4.jpg"]function changeImage(){    if (currentImage >= imageArray.length - 1) {        writeToDB();      } else {        currentImage += 1;      }    document.getElementById("mainImage").src = imageArray[currentImage]    img = imageArray[currentImage].slice(-8)    console.log(img)    window.sessionStorage.setItem("selected", JSON.stringify(img));}function writeToDB() {    var selected = JSON.parse(window.sessionStorage.getItem("selected"));    var firebaseConfig = {        apiKey: "***",        authDomain: "**",        databaseURL: "**",        projectId: "**",        storageBucket: "**",        messagingSenderId: "**",        appId: "**",        measurementId: "**"    };
查看完整描述

2 回答

?
函數式編程

TA貢獻1807條經驗 獲得超9個贊

因此,考慮到您想要獲得比實際告訴數據庫更多的數據,答案會更加復雜。每個文檔的數據結構可能更像這樣:


{

? url: /* string containing image's url */,

? rating: [4, 2, 5, 0] /* array containing ratings given for this image

}

每個圖像應該以大致相同的方式表示 - 所以如果你有一個名為 的集合images,那么你可能會有這樣的東西:


const dbRef = firebase.firestore();

const imagesRef = dbRef.collection('images');


const oneImage = imagesRef.doc('JdBPHMYWfNMMlMpfsjv5');

oneImage.get().then(function(doc){

? console.log( doc.data() )

? // that might return?

? {

? ? 'url': '/img/sun002.jpg',

? ? 'rating': [5,2,3,2,0,5]

? }


? /***

? ?* but! In your case, you'd likely want to create the HTML fragment

? ?* you'll be injecting for this particular image:

? ?***/

? // so let's pull all the stuff out of the database, and create an object

? //? that includes the image's id.

? const image = {id: doc.id, ...doc.data() }


? // Using that, we can create an HTML fragment that generates the radio buttons

? const imageEl = document.createRange().createContextualFragment(`<div class='img-container'>

? <img src='${image.url}'>

? <fieldset class='image-rating'>Rate this image:?

? ? <label>0 <input type='radio' name='rating' data-uid='${image.id}' value=0 /></label>

? ? <label>1 <input type='radio' name='rating' data-uid='${image.id}' value=1 /></label>

? ? <label>2 <input type='radio' name='rating' data-uid='${image.id}' value=2 /></label>

? ? <label>3 <input type='radio' name='rating' data-uid='${image.id}' value=3 /></label>

? ? <label>4 <input type='radio' name='rating' data-uid='${image.id}' value=4 /></label>

? ? <label>5 <input type='radio' name='rating' data-uid='${image.id}' value=5 /></label>

? </fieldset>

</div>

'`)


// Let's add a listener for the click on the wrapper for all these radios

imageEl.querySelector('.image-rating').addEventListener('click', handleRatingClick)


// And finally, let's add this image block to the page!

document.querySelector("#images-content-pane").appendChild(imageEl)


})

doc請注意,每個圖像在集合中都是其自己的,但它可以包含您可能喜歡的任何屬性。您可以添加一個caption屬性,或者任何可能對您有用的內容。

但有幾點需要注意:

  1. 我以編程方式創建每個圖像的容器,并將偵聽器動態添加到每個圖像的字段集。

  2. 我正在data-uid向每個單選按鈕添加一個屬性。我們稍后需要它,以便我們知道要更新哪個圖像文檔!

然后,稍后,當您為此圖像添加評級時,您只需引用該特定圖像并將所選評級添加到數組中即可:

// In my case, I had a fieldset wrap all my radio buttons, and a click was handled there:

const handleRatingClick = (event) =>{

? // First, let's get the clicked el:

? const ratingBtn = event.target;

? const imageId = ratingBtn.dataset.uid;

? const rating = ratingBtn.value;



? // And here I update the array in the rating property, by adding the given value

? imagesRef.doc(imageId).update({

? ? rating: firebase.firestore.FieldValue.arrayUnion(Number(rating))

? })


}

請注意,這不是唯一的方法,甚至不是正確的方法。重點是,您需要將每個圖像視為數據庫中的文檔,并且需要在創建或更新它時為 firestore 提供一個對象。


您可以像您正在做的那樣,并使用 localStorage/sessionStorage 中的圖像,但即便如此, sessionStorage 中的值也需要是一個對象,包含


{

? url,

? answer

}

這樣做.set()只會覆蓋每次答案的值,而不是隨著時間的推移存儲它們。另外,為了讓你的工作正常,你需要在某個地方存儲一個 doc.id 。

查看完整回答
反對 回復 2023-08-05
?
明月笑刀無情

TA貢獻1828條經驗 獲得超4個贊

通過將圖像名稱和評級值添加到字典中來解決



查看完整回答
反對 回復 2023-08-05
  • 2 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號