简体   繁体   English

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

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

I am trying to retrieve several "game" objects from Firebase Storage, calculate some statistics on them, and then display the game statistics in a table.我试图从 Firebase 存储中检索几个“游戏”对象,计算它们的一些统计数据,然后在表格中显示游戏统计数据。 The outline of my code is as follows:我的代码大纲如下:

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

The setLastModifiedText is the only hook that currently works, updating the text in the render() when I refresh in the browser. setLastModifiedText是目前唯一有效的挂钩,当我在浏览器中刷新时更新render()中的文本。 None of the statistical calculations display, however, unless I change something in the render() and save the file.但是,除非我更改render()中的某些内容并保存文件,否则不会显示任何统计计算。 When I attempt to perform the calculations and iterations inside the .then() call, where the setModifiedText, I run into more issues.当我尝试在 .then .then()调用中执行计算和迭代时,在 setModifiedText 的位置,我遇到了更多问题。

I am having difficulty figuring out what the issue is.我很难弄清楚问题是什么。 I figure one of my async or useEffect() calls is out of place, but do not know where.我认为我的asyncuseEffect()调用之一不合适,但不知道在哪里。 Thanks for any help you can provide!感谢您的任何帮助,您可以提供!

I attempted to change various async and useEffect() calls, as well as refactoring my functions, but no combination solved the problem.我尝试更改各种asyncuseEffect()调用,以及重构我的函数,但没有任何组合可以解决问题。

I don't know if this is the optimal answer but this pattern worked for me:我不知道这是否是最佳答案,但这种模式对我有用:

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

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

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

The key is to make the async call for data in the background, then use another useEffect that has a dependency to the data being retrieved.关键是在后台对数据进行异步调用,然后使用另一个对正在检索的数据具有依赖性的 useEffect。 When that data changes upon completion of the async call, the useEffect with a dependency on the retrieved data will run and force a rerender.当数据在异步调用完成后发生变化时,依赖于检索到的数据的 useEffect 将运行并强制重新渲染。

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

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