【问题标题】:How to cause re-render when I change the state using react hooks?当我使用反应钩子更改状态时如何导致重新渲染?
【发布时间】: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


    【解决方案1】:

    useEffect 钩子不会触发,直到数组中传递的值是 useEffect 钩子的第二个参数没有改变。在这种情况下会话。

    查看代码,我没有看到 joinSetSession 更改或更新会话值。您需要想办法让 joinSetSession 更改会话值,或者让逻辑与 sessionLocal 变量不紧密耦合。

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

    【讨论】:

    • 谢谢。我现在明白为什么重新渲染不会发生了。可能我需要找到一些方法将两种状态更改耦合在一起。
    • 我尝试通过添加 2 个 useEffect 挂钩来进行更改,但徒劳无功。这是我添加的钩子:``` useEffect(() => { setSessionsList(foundgames); // eslint-disable-next-line react-hooks/exhaustive-deps }, [foundgames]); useEffect(() => { setLocalSession(sessionsList[joinIndex]); // eslint-disable-next-line react-hooks/exhaustive-deps }, [joinIndex]); ``` 不知何故,我想我可以在 joinsessions 数组的索引更改时触发渲染。仍然没有为我重新渲染。
    猜你喜欢
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 2020-07-20
    • 2021-01-27
    • 2019-04-03
    • 1970-01-01
    相关资源
    最近更新 更多