【问题标题】:Unable to update values of useState passed through React Context无法更新通过 React Context 传递的 useState 的值
【发布时间】:2022-10-01 13:24:56
【问题描述】:

这是我的GameContext 文件:

import { createContext } from \"react\";

export const GameContext = createContext(null)

在我的App.js 中,我初始化了我希望包装我的上下文的所有值,以便所有其他子组件都可以使用它:

  const gameContextValue = {
    isGameStarted,
    setGameStarted,
    isPlayerTurn,
    setPlayerTurn,
    roomId,
  };

  return (
    <GameContext.Provider value={gameContextValue}>
      <BrowserRouter>
        <Routes>
          <Route path=\"/register\" element={<Register />} />
          <Route path=\"/login\" element={<Login />} />
          <Route path=\"/\" element={<JoinGame />} />
          <Route path=\"/game\" element={<Game />} />
        </Routes>
      </BrowserRouter>
    </GameContext.Provider>
  );
}

然后,我使用useContext() 在我的子组件中使用这些值:

 const {
    isGameStarted,
    setGameStarted,
    isPlayerTurn,
    setPlayerTurn,
    roomId,
  } = useContext(GameContext);

const Game = () => {
  const handleGameStart = () => {
      setGameStarted(true);
      console.log(\"value of isGameStarted: \", isGameStarted)   //shows false
      if (start) {
        setPlayerTurn(true);
      } else {
        setPlayerTurn(false);
      }
    });
  };
}

  useEffect(() => {
    handleGameUpdate();
    handleGameStart();
  }, []);

为什么我的 useState 更新不起作用?我不确定我做错了什么......我真的很感激任何建议(盯着我的代码 2 小时无济于事......)

    标签: reactjs react-hooks react-context


    【解决方案1】:

    您的值可能设置正确。问题是您在设置状态后立即记录。 React 不会立即更新值,它稍后会刷新。

    如果您登录渲染,您将看到它正在工作。

    见:https://beta.reactjs.org/apis/react/useState#ive-updated-the-state-but-logging-gives-me-the-old-value

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-28
      • 2021-08-13
      • 2021-05-23
      • 1970-01-01
      • 2020-12-22
      • 2021-11-15
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多