繁体   English   中英

从 Firebase 检索数据、对其执行计算并在 React(挂钩)中显示它的正确方法是什么?

[英]What is the correct way to retrieve data from Firebase, perform computations on it, and display it in React (hooks)?

我试图从 Firebase 存储中检索几个“游戏”对象,计算它们的一些统计数据,然后在表格中显示游戏统计数据。 我的代码大纲如下:

function calculateTeamStatistics(team) {
   // Iterating over all games, looking for team name in file, crunching the statistics
}

useEffect(() => {
   async function prepareStatistics() {
    // Iterating over all games, identifying teams (there is no list of teams)
    calculateTeamStatistics(team)
   }
   prepareStatistics();
}, []);


  useEffect(() => {
    async function getAllGames(tournament: string) {
      let gameFileReferences: any = [];
      let allGames: any[] = [];
      const storageRef = storage.ref();
      let gameRef = storageRef.child(`${tournament}_results/`).listAll();
      await gameRef.then((gameFiles) => {
        gameFileReferences = gameFiles.items;
        gameFileReferences.forEach((game: any) => {
          storageRef
            .child(`${tournament}_results/${game.name}`)
            .getDownloadURL()
            .then((url) => {
              axios
                .get(url, {
                  headers: {
                    Accept: "application/json",
                  },
                })
                .then((response) => {
                  allGames.push(response);
                  if (lastModifiedText === "" && response.headers) {
                    setLastModifiedText(response.headers["last-modified"]);
                  }
                })
                .catch((error) => console.log(error));
            });
        });
      });
      setTournamentGames(allGames);
    }

    getAllGames(tournamentId);
  }, []);

setLastModifiedText是目前唯一有效的挂钩,当我在浏览器中刷新时更新render()中的文本。 但是,除非我更改render()中的某些内容并保存文件,否则不会显示任何统计计算。 当我尝试在 .then .then()调用中执行计算和迭代时,在 setModifiedText 的位置,我遇到了更多问题。

我很难弄清楚问题是什么。 我认为我的asyncuseEffect()调用之一不合适,但不知道在哪里。 感谢您的任何帮助,您可以提供!

我尝试更改各种asyncuseEffect()调用,以及重构我的函数,但没有任何组合可以解决问题。

我不知道这是否是最佳答案,但这种模式对我有用:

const [data, setData] = useState(**your default value**);
const [object, setObject] = useState(**your default value**);

useEffect(() => (setData(**your async call**), []);

useEffect(() => (setObject(data)), [data]);

关键是在后台对数据进行异步调用,然后使用另一个对正在检索的数据具有依赖性的 useEffect。 当数据在异步调用完成后发生变化时,依赖于检索到的数据的 useEffect 将运行并强制重新渲染。

暂无
暂无

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

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