【问题标题】:How to toggle the state to false on component unmount using react?如何使用 react 将组件卸载时的状态切换为 false?
【发布时间】:2020-11-16 17:42:47
【问题描述】:

我正在使用上下文切换对话框的状态。最初状态 isOpen 设置为 false。单击添加按钮时,状态 isOpen 为 true,单击取消按钮会将状态 isOpen 设置为 false。

现在当用户不点击取消按钮时,即使用户导航到另一个页面,isOpen 状态仍然为真。

下面是我的代码,

function Main() {
    return(
        <DialogContextProvider>
            <Parent/>
        </DialogContextProvider>
   );
}


function Parent() {
    return (
        <AddButton/>
    );
}


function AddButton() {
    const { isOpen, toggleDialog } = useDialogs();
    return(
        <Icon 
            onClick={() => {
                toggleDialog(true); //isOpen set to true
            }}/>
        {isOpen &&
            <Dialog
                onCancel={() => {
                toggleDialog(false); //isOpen set to false
        }}
    );
}


interface DialogsState {
    isOpen: boolean;
    setOpen: React.Dispatch<React.SetStateAction<boolean>>;
}

const initialState: DialogsState = {
    isOpen: false,
    setIsOpen: () => {},
};

const DialogsContext = React.createContext<DialogsState>(
    initialState
);

export const DialogsContextProvider: React.FC = ({ children }) => {
    const [isOpen, setOpen] = React.useState<boolean>(false);

    return (
        <DialogsContext.Provider
            value={{isOpen,setOpen}}>
            {children}
        </DialogsContext.Provider>
    );
};

export function useDialogs() {
    const {
        isOpen,
        setOpen,
    } = React.useContext(ScheduleDialogsContext);
    const toggleDialog = (toggleValue: boolean) => {
        setOpen(toggleValue);
    };

    return {
        isOpen,
        toggleDialog,
    };
} 

当此对话框卸载时,我不确定如何将状态 isOpen 设置为 false,这意味着当用户打开此对话框时 isOpen 状态为 true。如果用户没有在对话框上单击取消并移动到另一个页面,则此 isOpen 状态为真。在这种情况下它应该是错误的。

我该如何解决这个问题。有人可以帮我吗?谢谢。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您可以使用useEffect 并从中返回一个函数,该 fn 将在组件卸载时调用 例如

    useEffect(() => {
    // called on mount
      return () => {
        // called on unmount
      }
    }, [])
    

    这里是参考链接https://reactjs.org/docs/hooks-effect.html

    【讨论】:

      【解决方案2】:

      useEffect 钩子有return,当组件卸载时触发。

      export const DialogsContextProvider: React.FC = ({ children }) => {
          const [isOpen, setOpen] = React.useState<boolean>(false);
      
          useEffect(() => {
            return () => {
              setOpen(false);
            }
          }, []);
      
          return (
              <DialogsContext.Provider
                  value={{isOpen,setOpen}}>
                  {children}
              </DialogsContext.Provider>
          );
      };
      

      【讨论】:

      • 在上下文提供者中使用 useeffect dint 工作,因为这个父组件不会卸载整个应用程序。我在 Dialog 组件中使用了它,但如果也单击了对话框上的某个按钮,则会以某种方式关闭对话框。
      • 尝试在ReactDOM.createPortal中安装你的对话框
      猜你喜欢
      • 2020-11-16
      • 2020-06-12
      • 2018-12-04
      • 2017-03-14
      • 1970-01-01
      • 2021-12-10
      • 2015-11-14
      • 2018-01-22
      • 2019-11-15
      相关资源
      最近更新 更多