当我使用反应挂钩更改状态时如何导致重新渲染?

How to cause re-render when I change the state using react hooks?

我正在创建一个组件,其中包含两个用于创建游戏会话的按钮。当用户创建游戏时,它会自动将他重定向到游戏会话。如果游戏不是由用户创建的,而是用户 'joins' 由另一个用户创建的所谓游戏会话,我还希望允许重定向到会话。我的功能组件如下所示:

const GameCreate = ({session}) => {
/************** HOOKS *******************************/
    const [sessionLocal, setSessionLocal] = useState(null);

  useEffect(() => {
    setSessionLocal(session);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [session]);


/************** EVENT HANDLERS *******************************/
  const createGameSession = (gamesettings) => {
    const { playerLimit, deckId } = gamesettings;
    createSession(.....);//call to back end that populates 'session' props which inturn triggers the 
                         //useEffect hook above
  };

  const joinSetSession = (sessionToJoinIndex) => {
    setSessionLocal(foundgames[sessionToJoinIndex]);
  };

  if (sessionLocal) {
    return <Redirect to="/gamesession" />;
  }

  return profile === null ? (
    <Spinner />
  ) : ( <Fragment>
         <div><p>{profile.name}</p></div>
          <CreateGame // a modal component that calls the createGameSession() as a callback
          // .... some other data is passed to this component
            setGame={(gamesettings) => createGameSession(gamesettings)}
          />
          <JoinGame // a modal component that calls the joinSetSession() as a callback
         // .... some other data is passed to this component
            setSessionToJoin={(sessionToJoinIndex) =>
              joinSetSession(sessionToJoinIndex)
            }
          />
     </Fragment>
       );

};

我的问题是,目前 createGameSession 成功触发了我的 useEffect(因为 'session' 作为负载从 API 返回)。结果,我的 sessionLocal 也被填充,这成功地导致了重定向。 joinSetSession 不会发生同样的情况,因为当 setSessionLocal 设置 sessionLocal 状态时,useEffect 挂钩似乎不会触发。有人可以向我解释为什么会发生这种情况以及我该如何解决吗?非常感谢您的帮助。谢谢!

useEffect 钩子只有在数组中传递的值(useEffect 钩子的第二个参数)没有改变时才会触发。在这种情况下会话。

查看代码,我没有看到 joinSetSession 更改或更新会话值。您需要想出一种方法来使 joinSetSession 更改会话值或使逻辑与 sessionLocal 变量的耦合不那么紧密。

我可能会建议使用另一个 useState 挂钩,它将跟踪加入现有会话并根据其值操作可以完成。