React useEffect无法在依赖项更改上运行

时间:2020-05-19 10:40:13

标签: javascript reactjs frontend client

我要做什么

我有一个可供用户加入的大厅。为了在页面刷新上将已加入的大厅保留在客户端上,我决定将已加入的大厅放入浏览器的会话存储中。在useState中,它不会通过页面刷新而持续存在。

据我所知,设置会话存储被归类为副作用,应在useEffect中进行处理。问题是,当我将大厅设置为以大厅为依存关系的useEffect不能运行时。

设置断点表明它根本没有运行,但是我可以看到joinedLobbyundefined变成了一个对象(例如{success: "Successfully joined ...", payload : { id:"", ...}})。

会话存储区为空。

代码沙箱

Sandbox 自从我使用Emotion以来,CSS就坏了

更新

从后端获取数据会破坏应用程序。将数据设为静态可使应用程序正常运行。

关于为什么/如何我有0个想法。罪魁祸首似乎是第165 const jsonResponse行的play_index.jsx。

设置应更新useEffect的状态

  const { setJoinedLobby } = useContext(JoinedLobbyProviderContext);
  const history = useHistory();

  useEffect(() => {
    if (joinState.result === undefined) return;
    setJoinedLobby(joinState.result);
    history.push('/lobby');
  }, [joinState.result, history, setJoinedLobby]);

路由器内部的提供程序

          <JoinedLobbyProviderContext.Provider
            value={{ getJoinedLobby, setJoinedLobby }}>
            <Route path='/play'>
              <Play />
            </Route>
            <Route path='/lobby'>
              <Lobby />
            </Route>
          </JoinedLobbyProviderContext.Provider>

提供商提供的功能

  const [joinedLobby, setJoinedLobby] = useState(undefined);

  useEffect(() => {
    if (joinedLobby === undefined) return;
    sessionStorage.setItem('joinedLobby', JSON.stringify(joinedLobby));
  }, [joinedLobby]);

  const getJoinedLobby = () => {
    return JSON.parse(sessionStorage.getItem('joinedLobby'));
  };

编辑:joinState.result的变化方式


const joinInit = {
    errors: undefined,
    loading: false,
    result: undefined,
    id: undefined,
  };

  const joinReducer = (state, action) => {
    switch (action.type) {
      case 'joinLobby': {
        return { ...state, id: action.payload };
      }
      case 'loadingTrue':
        return { ...state, loading: true };
      case 'setResult':
        return { ...state, loading: false, result: action.payload };
      case 'setErrors':
        return {
          ...state,
          loading: false,
          errors: action.payload,
        };
      case 'reset':
        return joinInit;
      default : {throw new Error('Didn't find action passed to reducer')}
    }
  };

  const [joinState, joinStateDispatch] = useReducer(joinReducer, joinInit);

  const passRef = useRef();
  useEffect(() => {
    const joinLobby = async () => {
      joinStateDispatch({ type: 'loadingTrue' });
      try {
        const jsonResponse = await (
          await fetch(`${BACKEND_URL}/play/joinLobby/${joinState.id}`, {
            method: 'PATCH',
            credentials: 'include',
            headers: {
              'Content-type': 'application/json',
            },
            body: JSON.stringify({
              password: passRef.current.value,
            }),
          })
        ).json();
        joinStateDispatch({ type: 'setResult', payload: jsonResponse });
      } catch (e) {
        joinStateDispatch({ type: 'setErrors', payload: e });
      }
    };
    if (joinState.id !== undefined) {
      joinLobby();
    }
  }, [joinState.id, joinStateDispatch]);

0 个答案:

没有答案