簡體   English   中英

將獲取的數據寫入變量 firebase 實時數據庫反應

[英]Write fetched data to variable from firebase realtime database react

在此處輸入圖像描述 我試圖將獲取的數據保存到變量中,但我總是得到“太多重新渲染”或“未定義”。 我做錯了什么

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

const db = getDatabase();

function App() {
  const [data, setData] = useState();
  const getData = ref(db);

  useEffect(() => {
    const fetch = () => {
      get(child(getData, "tokens/")).then((snapshot) => {
        const fetched = snapshot.val();
        setData(fetched);
      });
      setTimeout(() => {
        console.log(data);
      }, 500);
    };
    fetch();
  }, []);
}

不需要setTimeout() 解析promise后可以打印數據如下圖:

function App() {
  const [data, setData] = useState();
  const getData = ref(db);

  useEffect(() => {
    const fetchData = () => {
      get(child(getData, "tokens/")).then((snapshot) => {
        const fetched = snapshot.val();
        console.log(fetched)
        setData(fetched);
      }); 
    };
    fetchData();
  }, []);
}

此外,我已將 fetch 重命名為 function 以避免與Fetch API混淆

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM