如何在卸载时使用useeffect将state设置为false



我想在对话框组件卸载时将isOpen的状态切换为false。

我想做什么?

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

现在,当用户没有单击"取消"按钮时,即使用户导航到另一个页面,状态仍然为"打开"。

下面是我的代码,

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
}}
);
}

function Dialog() {
useEffect(() => {
return () => {
toggleDialog(false);
};
});

handlefileselection = () => {
//some logic to upload files
}
return (
<input type='file' onChange={handlefileselection}/> //on clicking this the isOpen state is 
//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,
};
} 

在上面的代码中,我在卸载时使用useeffect并返回关闭对话框。但如果用户单击调用handlefileselection的输入按钮,这也会关闭对话框。

有人能告诉我为什么在组件并没有卸载的情况下调用useeffect吗。

有人能帮我修一下吗?谢谢

编辑:

我试过什么?

useEffect(() => {
return () => {
toggleDialog(false);
};
}, []); //error here

react useeffect缺少依赖项toggleDialog。要么包括它,要么删除依赖性阵列

但当我把它改成像这个

useEffect(() => {
return () => {
toggleDialog(false);
};
}, [toggleDialog]);

没有按预期工作。

不确定你想要实现的全部目标,但你可以做这样的事情。因为当对话框单击时,它会切换对话框。

function AddButton() {
const { isOpen, toggleDialog } = useDialogs(false);
const toggleOpen = () => {
toggleDialog(!isOpen); // will toggle from false to true, back and forth. 
}
return(
<Icon 
onClick={toggleOpen}/>
{isOpen && (
<Dialog
onCancel={null} // this will longer be needed as onClick handles the toggling
toggleDialog(false); // isOpen set to false
/>
)
}
);
}

最新更新