【发布时间】:2020-05-17 00:05:27
【问题描述】:
我正在创建一个包含两个按钮来创建游戏会话的组件。当用户创建游戏时,它会自动将他重定向到游戏会话。如果游戏不是由用户创建的,我还希望允许重定向到会话,而是用户“加入”另一个用户创建的所谓游戏会话。我的功能组件如下所示:
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(因为“会话”作为 API 的有效负载返回)。结果,我的 sessionLocal 也被填充,这成功地导致了重定向。 joinSetSession 不会发生同样的情况,因为当 setSessionLocal 设置 sessionLocal 状态时,useEffect 挂钩似乎不会触发。有人可以向我解释为什么会发生这种情况以及我该如何解决?非常感谢您的帮助。谢谢!
【问题讨论】:
标签: reactjs react-hooks use-state