反应-useEffect中的渲染滞后于UI

时间:2020-08-13 03:34:48

标签: javascript reactjs react-hooks

我正在尝试寻找一种更好的方式来对表单进行onChange验证,但是由于存在多个转贴,因此实在太麻烦了。

这是我的useEffect代码:

useEffect(() => {
        if (passwordValues.password) {
            setValidPassword({ confirmPassword: validateConfirmPassword(correctPassword), password: validatePassword(correctPassword) })
        }
        if(formData.name){
            setValidFormData(validFormData => ({...validFormData, name: validateData(correctFormData, "name")}))
        }
        
        if(formData.lastName){
            setValidFormData(validFormData => ({...validFormData, lastName: validateData(correctFormData, "lastName")}))
        }
        if(formData.email){
            setValidFormData(validFormData => ({...validFormData, email: validateData(correctFormData, "email")}))
        }
        if(formData.phone){
            setValidFormData(validFormData => ({...validFormData, phone: validateData(correctFormData, "phone")}))
        }
    }, [passwordValues, correctPassword, correctFormData, formData])

我知道我也许可以在几行中做到这一点,但是那是在做那么多的退赛吗?

每次输入更改时,我的formData,passwordValues,correctPassword和correctFormData都会更改。

-编辑-

我删除了数组中的大多数依赖项,而我仍然使用[formData],虽然提高了速度,但仍然有些滞后。

1 个答案:

答案 0 :(得分:0)

我在这里写它,因为它会有点冗长,不适合发表评论。

这些情况在任何应用程序中都很常见,在这种情况下,您必须对值的更改做出反应并解决此问题,我刚刚创建了一个特殊的钩子use-effect-x(正在编写测试)

此自定义钩子将告诉您更改的项目集,在这里可能非常有用。下面是代码,我能够根据您的输入编写代码。您可以在各处使用useEffectX代替useEffect。这样,不需要的setValidFormData将不会运行。试试看,让我知道。

import { useEffectX } from "use-effect-x";
useEffectX(
  ({
    changedItem: [
      changeObjConfirmPassword,
      changeObjPassword,
      changeObjName,
      changeObjLastname,
      changeObjEmail,
      changeObjPhone,
    ],
  }) => {
    if (changeObjConfirmPassword.changed) {
      setValidPassword({
        confirmPassword: validateConfirmPassword(confirmPassword),
      });
    }

    if (changeObjPassword.changed) {
      setValidPassword({
        password: validatePassword(correctPassword),
      });
    }

    if (changeObjName.changed) {
      setValidFormData((validFormData) => ({
        ...validFormData,
        name: validateData(correctFormData, "name"),
      }));
    }

    if (changeObjLastname.changed) {
      setValidFormData((validFormData) => ({
        ...validFormData,
        lastName: validateData(correctFormData, "lastName"),
      }));
    }
    if (changeObjEmail.changedd) {
      setValidFormData((validFormData) => ({
        ...validFormData,
        email: validateData(correctFormData, "email"),
      }));
    }
    if (changeObjPhone.changed) {
      setValidFormData((validFormData) => ({
        ...validFormData,
        phone: validateData(correctFormData, "phone"),
      }));
    }
  },
  [confirmPassword, password, name, lastName, email, phone]
);


   

谢谢,让我知道,如果这不是您所期望的建议,我会提出。