为什么我的 Firebase get() 函数在 React 组件内触发两次?

问题描述 投票:0回答:2

在初始化文件中,我是这样编码的。

import { initializeApp } from 'firebase/app';
import { getDatabase, ref, child, get  } from "firebase/database";

const config = {

};

const app = initializeApp(config);
const db = getDatabase(app);
const dbRef = (ref(db));

get(child(dbRef, "shop_data")).then((snap) => {
    console.log(snap.val())
})
export {dbRef};

从这里,我从 console.log 收到一个结果

现在,在我的 Store 组件中,我只将 get() 函数放入

import '../css/StoreSelectable.css';
import { dbRef } from '../js/firebase_init';
import { getDatabase, ref, child, get  } from "firebase/database";

function StoreSelectable(){    
    const getStore = () => {
        get(child(dbRef, "shop_data")).then((snap) => {
            console.log(snap.val())
        })
        return;
    }
   

    return(
        <div className="Store-Selectable">
            <table id="place_option" align="center" style={{tableLayout: 'fixed'}} className="radioButtons collapseBorder">  
                <tbody>
                    
                        {getStore()}
                    
                </tbody>         
            </table>
            
        </div>
        
    );

}

export default StoreSelectable;

现在,firebase 函数会触发两次。


编辑 2022 年 10 月 6 日 我尝试了useEffect,但它仍然获取两次数据。我真的不想使用Firestore,因为我必须重写很多代码。这种情况我该怎么办?

import "../css/StoreSelectable.css";
import { dbRef } from "../js/firebase_init";
import { getDatabase, ref, child, get } from "firebase/database";
import { useEffect, useState } from "react";

function StoreSelectable() {
  const pin = {
    TestiKirppis: ["Jarii1", "spr1234", "6899bc73da4ace09"],
    Vaasa: ["D0ED5D57F47580F2", "spr9876", "Vas183"],
    Seinäjoki: ["a1a1a1a1a1a1a1a1", "spr9999", "Seina19"],
    Kokkola: ["regT863", "spr0000", "b4b8bb4ceeaa2aee"],
  };

  const [count, setCount] = useState([]);

  useEffect(() => {
    const getStore = () => {
        get(child(dbRef, "shop_data")).then((snap) => {
            let val = snap.val();
            Object.keys(val).forEach((key) => {
                setCount((count) => [...count, val[key].name]);
            })
        });
    }    
    getStore();

    
  }, []);

  return (
    <div className="Store-Selectable">
      <table
        id="place_option"
        align="center"
        style={{ tableLayout: "fixed" }}
        className="radioButtons collapseBorder"
      >
        <tbody>{count.map((data) => {return (<p>{data}</p>)})}</tbody>
      </table>
    </div>
  );
}

export default StoreSelectable;
reactjs firebase
2个回答
1
投票

我认为这是因为react 18中的严格模式。如果你删除它,问题就会解决。

请检查:文件的多次执行导致react js中的多个服务器调用


0
投票

事实上,问题出在React 18中的严格模型上,我有同样的错误,我的React js应用程序进行了两次提交,但禁用严格模式后,问题得到了解决

© www.soinside.com 2019 - 2024. All rights reserved.