【问题标题】:onClose mui drawer function is executed multiple times on multiple clicksonClose mui抽屉功能在多次点击时执行多次
【发布时间】:2022-12-13 20:55:15
【问题描述】:

我有 mui Drawer + Formik + React

<Drawer anchor="right" open={isOpen} onClose={onClose}> 

当我们关闭抽屉时,执行onClose。我们还有 onBackdropClickhideBackdrop 道具

当我关闭抽屉onClose 运行时,如果我在抽屉外单击多次onClose 函数会执行多次。这是我写的解决方案:

  const formik = useFormik<SomeType>({
    initialValues,
    validationSchema: Schema,
    onSubmit: (values) => onFormSubmit(values), // this function will be executed if we write `formik.handleSubmit()`
  });

  const onClose = async () => {
    const { values, dirty, setSubmitting, isSubmitting } = formik;
    const { recurrenceType } = values;

    if (!dirty) {
      onSidebarClose(); // <=== close the sidebar if we didn't change anything in the form
    }

    if (isSubmitting) return;

    setSubmitting(true);

    if (condition1) {
      await request1(formik);
    } else if (condition2) {
      await request2(values);
    } else if (condition3) {
      await request3(values);
    }

    setSubmitting(false);
  };

在这种情况下,用户将无法一次发送多个请求。

这个解决方案不清楚,也许有人知道更好的解决方案?

问题: 只运行一次 onClose 函数以防止一次发出多个请求

【问题讨论】:

    标签: reactjs material-ui formik react-mui


    【解决方案1】:

    我建议使用 useEffect[isOpen] 作为依赖项之一。您可能还需要将 onClose={onClose} 更改为简单函数,而不是将 isOpen 值更改为类似 onClose={() =&gt; setIsOpen(false)} 的值。

    useEffect(() => {
       if (!isOpen && (some conditions in order to prevent function execution on component mount)) {
           onClose()
       } 
    }, [isOpen, other, dependencies])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-11
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多