1

我有这个非常简单的增量计数器(见下文)。我在 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;
4

1 回答 1

3

使用 Firestore,这很容易。

  1. 创建一个集合
  2. 在集合内创建一个文档
  3. 向文档添加一个字段,变量类型为“number”

那么,有两种情况:

I. EASY:用户无需登录即可递增计数器。

您需要做的是创建一个服务器功能。该函数的触发器将是一个 HTTP 调用。从您的网页,您发送一个简单的 http 调用,例如“http://your-function-url/?counter=increment”(使用 axios、jquery 甚至只是 XHR)

[在这里阅读如何做到这一点:https ://firebase.google.com/docs/functions/http-events ]

该函数将在您调用时触发。在函数内部,您需要使用 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 函数的文档非常广泛,我上面所说的也是如此。

不是那么容易:如果您需要用户登录以增加计数器,那么您需要配置 Firebase 身份验证,然后使用 Firebase Javascript Web SDK 写入 Firestore。

我希望这有帮助。随意谷歌我刚才说的任何东西,这一切都相当有据可查。祝你好运

更新:要读取计数器的新值,您需要使用客户端文档查询(搜索“document.onSnapshot”)。这是一种从 Firestore 获取实时价值并将其显示在您的网页上的方法。这也意味着具有“计数器”字段的文档需要公开或仅显示给登录用户。您可以在“Firebase 规则”中配置该访问权限,您可以在其中进行设置,以便特定文档具有与数据库其余部分不同的权限。

于 2020-12-08T20:00:39.820 回答