当组件卸载时,如果用户单击“提交”,我会尝试阻止 toast。尝试使用 useState 进行操作,但它对我不起作用。 我的目标是向用户显示 toast,但如果他单击“提交”,他不应该看到此 toast。当组件卸载时,Toast 应该会出现,并且我们会离开带有表单的页面而不提交。
const [formSubmitted, setFormSubmitted] = useState(false);
const formik = useFormik({
onSubmit: async (values) => {
setFormSubmitted(true);
// some logic
navigate('/toAnotherPage');
})}
useEffect(() => {
return () => {
if (formik.dirty && !formSubmitted) {
toast({ //toast from chakraUI
description: "Save info to draft",
status: "success",
duration: 3000,
isClosable: false,
containerStyle: {
fontSize: "16px ",
fontWeight: "350",
},
});
}
};
}, [formik.dirty, formSubmitted]);
我不会采用
useEffect
方法中的清理功能。尝试寻找路线改变的解决方案。
基本上,如果路线已更改并且未提交表单,则呈现一条 toast 消息。
import { useLocation } from 'react-router-dom'
const location = useLocation()
useEffect(()=>{
if (formik.dirty && !formSubmitted) {
// your toast here
}
// Listens for location path name change as well
},[location.pathname,formik.dirty,formSubmitted])
这应该能够满足您发出 toast 消息并通知用户他们的用例。