如果我给依赖项提供random_grid或random_grid_solutions_set,则useEffect()会触发无限循环。
我认为提供空[]作为依赖项将解决此问题,因为React会先渲染,调用useEffect()然后渲染一次。但是,提供这种依赖关系不会填充random_grid_solutions_set(源自useEffect()内的console.log从未被调用的事实。)
import React, { useEffect, useState } from 'react';
import PrintGrid from './PrintGrid';
import firestoreRef from './FirestoreRef';
import { findAllSolutions } from './boggle_solver';
import all_words from './full-wordlist';
import GamePlay from './GamePlay';
function PlayGame(props) {
var grid_data = props.location.state;
const [random_grid, setRandomGrid] = useState([]);
const [random_grid_solutions_set, setRandomGridSolutionSet] = useState(
new Set()
);
console.log('Grid id in PlayGame component is: ', grid_data.grid_id);
var str_grid_id = String(grid_data.grid_id);
async function load_grid() {
await firestoreRef
.collection('grids')
.doc(str_grid_id)
.get()
.then(function(doc) {
var new_grid_data = [];
new_grid_data.push(doc.data().array_0);
new_grid_data.push(doc.data().array_1);
new_grid_data.push(doc.data().array_2);
new_grid_data.push(doc.data().array_3);
new_grid_data.push(doc.data().array_4);
setRandomGrid(new_grid_data);
});
}
useEffect(() => {
load_grid();
var random_grid_solutions = findAllSolutions(random_grid, all_words.words);
setRandomGridSolutionSet(new Set(random_grid_solutions));
console.log(
'PlayGame: Random grid solution set: ',
random_grid_solutions_set
);
}, []);
// var random_grid_solutions = findAllSolutions(random_grid, all_words.words);
// var random_grid_solutions_set = new Set(random_grid_solutions);
return (
<div>
<p> This is play game page. {grid_data.grid_id} </p>
<PrintGrid grid_id={grid_data.grid_id} />
<GamePlay
random_grid={random_grid}
random_grid_solutions={random_grid_solutions_set}
/>
</div>
);
}
export default PlayGame;