Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

reactjs - React freezing when updating context

using react hooks

Experiencing a weird bug that seems to cause some sort of infinite loop or something. Has anyone run into something like this before.

Here's what I have:

import { createContext, useState, useCallback } from "react";

export type ModalValue = string | null;

const DEFAULT_ACTION = null;

export const useModalContext = (): ModalContextContents => {
  const [
    modal,
    setModalInner,
  ] = useState<ModalValue>(DEFAULT_ACTION);

  const setModal = useCallback((nv: ModalValue) => {
    setModalInner(nv);
  }, []);

  return {
    modal,
    setModal,
  };
};

interface ModalContextContents {
  modal: ModalValue;
  setModal: (nv: ModalValue) => void;
}

export const ModalContext = createContext<ModalContextContents>({modal: null, setModal: () => {}});

modal.tsx

import React, {useContext, useCallback} from 'react';
import {Box, Button, Aligner} from 'components';
import {ModalContext} from './modalContext';

import './modal.scss';

export const Modal = () => {
  const modalApi = useContext(ModalContext);
  if (modalApi.modal === null) {
    return <></>
  }
  return <div key="lobby-modal" className='modal'>
      <Aligner>
      <Box style={{background: 'rgba(0, 0, 0, 0.72)'}}>
      {modalApi.modal || ''}
      <Button text="close" onClick={() => {modalApi.setModal(null)}}/>
      </Box>
      </Aligner>
    </div>;
}

For some reason when I call: modalApi.setModal('some-text'); then: modalApi.setModal(null);

the entire page freezes.

Anyone have any idea what's going on here?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

elsewhere in the app I had:

const callbackMapping: {[key: string]: Action} = useMemo(() => {
  return {
    callback: () => modelApi.setModal('wardrobe')
  }
}, [room, modelApi])

then I was invoking it in a useEffect.

so I was causing an infinite in the app by changing the context value and then re-changing it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...