简体   繁体   English

React useContext 无法使用 setTimeout function 更新 state

[英]React useContext doesn't work using setTimeout function to update the state

I am new to React, so maybe excuse my dumb question.我是 React 的新手,所以请原谅我的愚蠢问题。 I want to refresh the score of my card game in a for Each loop with a setTimeout function in each run.我想在每次运行中使用 setTimeout function 在 for Each 循环中刷新纸牌游戏的分数。 The state seems to be updated, but the DOM (Component overarching) is not. state 似乎已更新,但 DOM(Component overarching)并未更新。

export function RefillStack() {
  const { gameStore, setGameStore } = useContext(GameContext);
  const finishMove = () => {
    let game: Game = { ...gameStore };
      // some code
    game.players.forEach((player, playerIndex) => {
      game.players[playerIndex] = player.cards.filter(card => card > 6);
      // some code
      setTimeout(()=> {setGameStore(game)}, 1000);
    });

If I use the useState function then everything works, but I have to use the useContext function. I think I need a workaround for this, but what is the smartest way to do it?如果我使用 useState function 那么一切正常,但我必须使用 useContext function。我想我需要一个解决方法,但最聪明的方法是什么? Thank you very much for any help!非常感谢您的帮助!

I have come closer to my solution myself.我自己已经接近我的解决方案。

I had to assign a clone of the gameStore to the variable "Game" again after the setGameState function.我不得不在 setGameState function 之后再次将 gameStore 的克隆分配给变量“Game”。

It's certainly not elegant, but it works for me.它当然不优雅,但对我有用。 The forEach looks now like this. forEach 现在看起来像这样。

 game.players.forEach((player, playerIndex) => {
  game.players[playerIndex] = player.cards.filter(card => card > 6);
  // some code
  setTimeout(()=> {setGameStore(game)}, 1000 * (playerIndex + 1));
  game = {...gameStore};
});

You might try using the useEffect hook to schedule the context state change.您可以尝试使用useEffect挂钩来安排上下文 state 更改。 After a component has been rendered, you may use this hook to conduct side effects (such as altering the context state).呈现组件后,您可以使用此挂钩来执行副作用(例如更改上下文状态)。

Here's an example of how you could use useEffect to schedule context state updates in your code:下面是一个示例,说明如何使用useEffect在代码中安排上下文 state 更新:

import { useEffect } from 'react';

export function RefillStack() {
  const { gameStore, setGameStore } = useContext(GameContext);
  const finishMove = () => {
    let game: Game = { ...gameStore };
    // some code
    game.players.forEach((player, playerIndex) => {
      game.players[playerIndex] = player.cards.filter(card => card > 6);
      // some code
    });
    // Schedule the update to the context state using useEffect
    useEffect(() => {
      setTimeout(() => {
        setGameStore(game);
      }, 1000);
    }, []); // The empty array ensures that the effect only runs once
  }
}

This should allow you to asynchronously update the context state and trigger a re-render of the component that utilizes the context state.这应该允许您异步更新上下文 state 并触发使用上下文 state 的组件的重新渲染。

I hope this was helpful!我希望这可以帮到你!

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

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