簡體   English   中英

將增量計數器存儲在 Firebase Cloud Firestore 或實時數據庫中

[英]Store Increment Counter In Firebase Cloud Firestore or Realtime Database

我有這個非常簡單的增量計數器(見下文)。 我在 WebStorm 上使用 React.js 構建了它。 如果加載它,它會顯示一個 0,並且每次單擊按鈕時計數都會增加 1。

我想做的是將這個數字保存在 Firebase 中。 這樣每次關閉頁面時計數都不會丟失。 相反,我想從到目前為止所有計數的數量開始,並且它們總是在 Firebase(Cloud Firestore 或實時數據庫)中自動更新。

有誰知道我必須如何設置 Firebase 存儲以及如何調整代碼? 非常感謝!

import React from "react";
import './App.css';

class SimpleCountdownTimer extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            clicks:0,
            show:true
        };
    }

    IncrementItem = () => {
        this.setState({clicks:this.state.clicks + 1});
    }

    ToggleClick = () => {
        this.setState({show: !this.state.show});
    }


  render() {

  return (

<div>

<button onClick={this.IncrementItem}>Increase!</button>
 
    {this.state.show ? <h2>{this.state.clicks}</h2>:''}

</div>
    );
  }
}

export default SimpleCountdownTimer;

使用 Firestore,這很容易。

  1. 創建一個集合
  2. 在集合內創建一個文檔
  3. 向文檔添加一個字段,變量類型為“number”

那么,有兩種情況:

I. EASY :用戶無需登錄即可遞增計數器。

您需要做的是創建一個服務器 function。 這個 function 的觸發器將是一個 HTTP 調用。 From your web page, you send a simple http call to for example "http://your-function-url/?counter=increment" (using axios, jquery, or even just XHR)

[在這里閱讀如何做到這一點: https://firebase.google.com/docs/functions/http-events ]

function 將在您調用時觸發。 在 function 內部,您需要使用 set() 方法將數據添加到 Firestore,如下所示...

db.collection('YOUR_COLLECTION').doc('YOUR_DOCUMENT_ID').set({
  counter: admin.firestore.FieldValue.increment(1); // "counter" is the name of the field you created, 1 is the number by which to increment the value of the "counter" field
}, {merge:true}) // merge: true means that your document is not overwritten, only updated.
.then({
  console.log('succesfully incremented the counter');
  return res.end(); // this is important
})
.catch({
  console.error('error incrementing the counter: '+err);
  return res.end();
});

關於如何在 firebase 上創建 HTTP function 的文檔非常廣泛,我上面所說的也是如此。

NOT SO EASY : if you need the user to be logged-in to increment the counter, then you'll need to configure Firebase Auth, then use the Firebase Javascript Web SDK to write to Firestore.

我希望這有幫助。 隨意谷歌我剛才說的任何東西,這一切都相當有據可查。 祝你好運

更新:要讀取計數器的新值,您需要使用客戶端文檔查詢(搜索“document.onSnapshot”)。 這是一種從 Firestore 獲取實時值並將其顯示在 web 頁面上的方法。 這也意味着具有“計數器”字段的文檔需要公開或僅顯示給登錄用戶。 您可以在“Firebase 規則”中配置該訪問權限,您可以在其中進行設置,以便特定文檔具有與數據庫的 rest 不同的權限。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM