如何在React中渲染Firestore数据? [英] How do I render Firestore data in React?

查看:42
本文介绍了如何在React中渲染Firestore数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对React和Firebase/Firestore还是很陌生.我已经浏览了Firestore文档几次,但仍然感到迷茫.这就是我知道的方法...我知道如何添加到Firestore数据库,并且我知道如何将数据打印到控制台.但是我不知道该如何渲染这些数据?任何人都可以指导我如何执行此操作吗?谢谢

I am fairly new to React and Firebase/Firestore. I have gone through the Firestore docs a few times and still feel lost. Here's what I know how to do... I know how to add to my Firestore DB, and I know how to print data to the console. But I don't know how to render that data? Can anyone please guide me on how to do this? Thanks

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;

推荐答案

您可以将数据保存为状态

you can save the data in the state

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

保存数据以在加载数据时显示状态

save the data to state when data loaded

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

and then render them as you want, I will display them as json in <pre> tag

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中渲染Firestore数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆