简体   繁体   English

将获取的数据写入变量 firebase 实时数据库反应

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

在此处输入图像描述 I'm trying to save fetched data into variable, but I always get "too many rerenders" or "undefined".我试图将获取的数据保存到变量中,但我总是得到“太多重新渲染”或“未定义”。 What I'm doing wrong我做错了什么

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();
  }, []);
}

There's no need of setTimeout() .不需要setTimeout() You can print the data when the promise is resolved as shown below:解析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();
  }, []);
}

Also I've renamed the fetch function to avoid any confusion with Fetch API此外,我已将 fetch 重命名为 function 以避免与Fetch API混淆

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM