如何在 React 中呈现 Firestore 数据?

IT技术 javascript reactjs firebase google-cloud-firestore
2021-05-13 11:53:51

我对 React 和 Firebase/Firestore 相当陌生。我已经浏览了几次 Firestore 文档,但仍然感到迷茫。这是我知道该怎么做...我知道如何添加到我的 Firestore 数据库,我知道如何将数据打印到控制台。但我不知道如何呈现这些数据?谁能指导我如何做到这一点?谢谢

import React, { Component } from 'react';
import './App.css';

import { database } from './firebase/firebase';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      inputField: ''
    };
  }

  onInputChange = (e) => {
    const inputField = e.target.value;
    this.setState(() => ({ inputField }));
  }

  /* Adding Data */
  onSubmit = (e) => {
    e.preventDefault();
    console.log(this.state.inputField);

    database.collection('users').add({
      name: this.state.inputField
    })
    .then((docRef) => {
      console.log("Doc written with ID: ", docRef.id)
    })
    .catch((error) => {
      console.error("Error adding document: ", error);
    });
  }

  /* Retrieving Data */
  onLoad = (e) => {
    const docRef = database.collection('users').doc('O6m4TFfIjE42ZaNfvC7s');

    docRef.get().then((doc) => {
      if (doc.exists) {
        console.log("Document data:", doc.data());
      } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
      }
      }).catch(function(error) {
        console.log("Error getting document:", error);
      });
  }

  render() {
    return (
      <div className="App">
        <h1>Raul: <p>{}</p></h1>
        <form onSubmit={this.onSubmit}>
          <input 
            type="text" 
            value={this.state.inputField} 
            onChange={this.onInputChange}  
          />
          <button>Save</button>
        </form>
        <button onClick={this.onLoad}>Load Data</button>
      </div>
    );
  }
}

export default App;
2个回答

您可以将数据保存在状态中

constructor(props)
{
    super(props);
    this.state = {
        inputField: '',
        data: null,
    };
}

将数据保存到加载数据时的状态

onLoad = (e) => {
    const docRef = database.collection('users').doc('O6m4TFfIjE42ZaNfvC7s');

    docRef.get().then((doc) => {
        if (doc.exists) {
            let data = doc.data();
            this.setState({ data: data });
            console.log("Document data:", data);
        } else {
            // doc.data() will be undefined in this case
            this.setState({ data: null });
            console.log("No such document!");
        }
    }).catch(function (error) {
        this.setState({ data: null });
        console.log("Error getting document:", error);
    });
}

然后根据需要渲染它们,我会将它们显示为<pre>标签中的json

render() {

    let dataUI = this.state.data ? <h1>No Data</h1> : <pre>{JSON.stringify(this.state.data)}</pre>;

    return (
        <div className="App">
            <h1>Raul: </h1>

            <div>
                <h1>UI Data</h1>
                {dataUI}
            </div>

            <form onSubmit={this.onSubmit}>
                <input
                    type="text"
                    value={this.state.inputField}
                    onChange={this.onInputChange}
                />
                <button>Save</button>
            </form>
            <button onClick={this.onLoad}>Load Data</button>
        </div>
    );
}

直接在 React 中使用 Firebase/Firestore API 可能会非常麻烦并导致大量样板文件。您可以使用 Firestorter,它在幕后使用 mobx 在几秒钟内将您的组件连接到 Firestore。

https://github.com/IjzerenHein/firetorter