React Hook的useEffect()需要单击两次按钮以更新渲染并

有一个链接组件可通往该组件。但是我需要单击链接两次以在div标签后立即查看grid_data的呈现。

另外,我将地图初始化为状态变量,并使用从Firestore提取的数据对其进行更新。 Firestore提取在控制台中打印数据时进展顺利。当读取后此映射不为空但使用.size函数无济于事时,我正在尝试在屏幕上的grid_data中呈现数据。

我是React的新手,我正试图从Firestore提取3个5x5网格并将它们传递给PrintChallengeList组件进行渲染,但是同时学习异步/等待,钩子,Javascript和React一直令人困惑。

任何其他意见也受到高度赞赏。

import React, { useState, useEffect } from 'react';
import firestoreRef from './FirestoreRef';
import { Switch, Route, Link } from 'react-router-dom';
import PlayGame from './PlayGame';
import PrintGrid from './PrintGrid';
import PrintChallengeList from './PrintChallengesList';

function LoadChallenge() {
  const [grid_data, setGridData] = useState({});

  useEffect(() => {
    async function load_grids_from_firebase() {
      var grid = [];
      var grid_id = null;
      await firestoreRef
        .collection('grids')
        .get()
        .then(function(querySnapshot) {
          querySnapshot.forEach(function(doc) {
            // doc.data() is never undefined for query doc snapshots
            grid_id = doc.id;
            grid.push(doc.data().array_0);
            grid.push(doc.data().array_1);
            grid.push(doc.data().array_2);
            grid.push(doc.data().array_3);
            grid.push(doc.data().array_4);
            var temp_grid_data = grid_data;
            temp_grid_data[grid_id] = grid;
            setGridData(temp_grid_data);
            grid_id = null;
            grid = [];
          });
        });
    }
    load_grids_from_firebase();
  }, [grid_data]);

  console.log('Test grid data: ', grid_data['PNQGe0QPtkI1HiwkCgT4']);
  console.log('Test grid data: ', grid_data['AzeuGUmEqHMSosKDfWr9']);
  console.log('Test grid data: ', grid_data['CJuso8gjNjUcNbhyrdyZ']);

  return (
    <div>
      {/* {grid_data.size > 0 && <p> {grid_data['PNQGe0QPtkI1HiwkCgT4'][0]} </p>} */}
      {grid_data.size && <PrintChallengeList grid_data={grid_data} />}
      <Switch>
        <Route exact path="/playgame" redirectTo="/" component={PlayGame} />
      </Switch>
      <Link
        to={{
          pathname: '/playgame',
          state: {
            grid_id: 'CJuso8gjNjUcNbhyrdyZ'
          }
        }}
      >
        Click to load this grid
      </Link>
    </div>
  );
}

export default LoadChallenge;
评论