📜  如何使用 ReactJS 使用 Firestore 执行获取和发送?

📅  最后修改于: 2022-05-13 01:56:39.971000             🧑  作者: Mango

如何使用 ReactJS 使用 Firestore 执行获取和发送?

在本文中,我们将学习如何从 Firestore 获取数据并将其显示在 React 应用程序中。 Firestore 是由 Google 开发的 NoSQL 数据库,作为 firebase 数据库的替代品。它旨在提供更好的开发人员体验并简化开发过程。以下步骤演示了创建应用程序的过程。

第 1 步:创建一个新的 React 应用程序。我们使用 create-react-app 来创建我们的应用程序。

npx create-react-app gfgfirestore

第 2 步:使用 npm 在项目中安装 firebase 包。

npm install firebase@8.3.1 --save

第 3 步:通过填写必要的详细信息并检查存储在 Firestore 中的数据的格式,从 Firebase 仪表板创建一个新项目。在此示例中,我们有一个对象,其中nameagecourseEnrolled是存储数据的字段。

第 4 步:通过从 Firebase 仪表板复制相关凭据来初始化项目中的 Firebase。

Javascript
import firebase from 'firebase';
  
var firebaseConfig = {
    // Firebase credentials
  };
    
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
  
export default db;


Javascript
import db from './firbase';
import {useState} from 'react';
  
const Firestore = () => {
    const [name  , Setname] = useState("");
    const [age , Setage] = useState("");
    const [course , Setcourse] = useState("");
    const sub = (e) => {
        e.preventDefault();
          
        // Add data to the store
        db.collection("data").add({
            Nane: name,
            Age: age,
            CourseEnrolled: course
        })
        .then((docRef) => {
            alert("Data Successfully Submitted");
        })
        .catch((error) => {
            console.error("Error adding document: ", error);
        });
    }
  
    return (
        
            
                
{sub(event)}}>                     {Setname(e.target.value)}} />                       

                    {Setage(e.target.value)}}/>                       

                    {Setcourse(e.target.value)}}/>                       

                                     
            
        
    ); }    export default Firestore;


Javascript
// Import Firestore database
import db from './firbase';
import { useState } from 'react';
import './read.css';
  
const Read = () => {
  
    const [info , setInfo] = useState([]);
  
    // Start the fetch operation as soon as
    // the page loads
    window.addEventListener('load', () => {
        Fetchdata();
      });
  
    // Fetch the required data using the get() method
    const Fetchdata = ()=>{
        db.collection("data").get().then((querySnapshot) => {
             
            // Loop through the data and store
            // it in array to display
            querySnapshot.forEach(element => {
                var data = element.data();
                setInfo(arr => [...arr , data]);
                  
            });
        })
    }
      
    // Display the result on the page
    return (
        
            
            

Student Details

            
                   {             info.map((data) => (                          ))         }         
       ); }    // Define how each display entry will be structured const Frame = ({course , name , age}) => {     console.log(course + " " + name + " " + age);     return (         
            
                  

NAME : {name}

                      

Age : {age}

                     

Course : {course}

                
        
    ); }    export default Read;


第 5 步:创建一个基本的用户界面,用于向商店添加数据。

Javascript

import db from './firbase';
import {useState} from 'react';
  
const Firestore = () => {
    const [name  , Setname] = useState("");
    const [age , Setage] = useState("");
    const [course , Setcourse] = useState("");
    const sub = (e) => {
        e.preventDefault();
          
        // Add data to the store
        db.collection("data").add({
            Nane: name,
            Age: age,
            CourseEnrolled: course
        })
        .then((docRef) => {
            alert("Data Successfully Submitted");
        })
        .catch((error) => {
            console.error("Error adding document: ", error);
        });
    }
  
    return (
        
            
                
{sub(event)}}>                     {Setname(e.target.value)}} />                       

                    {Setage(e.target.value)}}/>                       

                    {Setcourse(e.target.value)}}/>                       

                                     
            
        
    ); }    export default Firestore;

输出:

  • 填写详细信息后提交表格

  • 添加到存储中的数据的视图

第 6 步:创建用于显示商店数据的基本用户界面。我们将使用get()方法从存储中获取数据。然后数据循环并在

Javascript

// Import Firestore database
import db from './firbase';
import { useState } from 'react';
import './read.css';
  
const Read = () => {
  
    const [info , setInfo] = useState([]);
  
    // Start the fetch operation as soon as
    // the page loads
    window.addEventListener('load', () => {
        Fetchdata();
      });
  
    // Fetch the required data using the get() method
    const Fetchdata = ()=>{
        db.collection("data").get().then((querySnapshot) => {
             
            // Loop through the data and store
            // it in array to display
            querySnapshot.forEach(element => {
                var data = element.data();
                setInfo(arr => [...arr , data]);
                  
            });
        })
    }
      
    // Display the result on the page
    return (
        
            
            

Student Details

            
                   {             info.map((data) => (                          ))         }         
       ); }    // Define how each display entry will be structured const Frame = ({course , name , age}) => {     console.log(course + " " + name + " " + age);     return (         
            
                  

NAME : {name}

                      

Age : {age}

                     

Course : {course}

                
        
    ); }    export default Read;

输出:在此示例中,数据库中存在的四个记录显示在我们的应用程序中。