【问题标题】:React useContext doesn't work using setTimeout function to update the stateReact useContext 无法使用 setTimeout 函数更新状态
【发布时间】:2022-12-12 18:24:43
【问题描述】:
我是 React 的新手,所以请原谅我的愚蠢问题。我想在每次运行时使用 setTimeout 函数在 for Each 循环中刷新纸牌游戏的分数。状态似乎已更新,但 DOM(Component overarching)并未更新。
export function RefillStack() {
const { gameStore, setGameStore } = useContext(GameContext);
const finishMove = () => {
let game: Game = { ...gameStore };
// some code
game.players.forEach(player => {
// some code
setTimeout(()=> {setGameStore(game)}, 1000);
});
如果我使用 useState 函数,那么一切正常,但我必须使用 useContext 函数。我想我需要一个解决方法,但最聪明的方法是什么?非常感谢您的帮助!
【问题讨论】:
标签:
javascript
reactjs
react-hooks
react-context
【解决方案1】:
在您提供的代码中,setTimeout 函数用于延迟更新游戏状态的 setGameStore 函数的执行。这样做很可能是为了让玩家有足够的时间在再次更改之前查看更新后的状态。
这种方法的一个潜在问题是 setTimeout 函数只会在指定的延迟后运行提供的回调(在本例中为 setGameStore)一次。在 forEach 循环中,这意味着只有循环的最后一次迭代才会真正更新游戏状态,之前的迭代将被忽略。
要解决此问题,您可以使用 setInterval 函数而不是 setTimeout。 setInterval 将以指定的时间间隔重复运行提供的回调,允许 forEach 循环的每次迭代更新游戏状态。以下是如何修改代码以使用 setInterval 的示例:
export function RefillStack() {
const {
gameStore,
setGameStore
} = useContext(GameContext);
const finishMove = () => {
let game: Game = { ...gameStore
};
// some code
game.players.forEach(player => {
// some code
// Use setInterval to run the setGameStore function at regular intervals
// This will allow each iteration of the forEach loop to update the game state
setInterval(() => setGameStore(game), 1000);
});
};
// Rest of the function...
}
在上面的示例中,我们使用 setInterval 函数定期运行 setGameStore 函数。这将允许 forEach 循环的每次迭代更新游戏状态,并且玩家将能够在更新发生时看到它们。请记住,如果 forEach 循环很大或运行过于频繁,像这样使用 setInterval 可能会导致性能问题。您可能需要考虑使用不同的方法,例如使用 setState 和 React 的内置渲染功能,以更高效和高性能的方式更新游戏状态。