我正在想一种更好的方法来对我的表单进行onChange验证,但由于有多个转发器,这真的很滞后。
这是我的用途效果代码:
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],提高了速度,但仍然有点滞后。
我在这里写它,因为它的解释有点长,不适合注释。
这些场景在任何应用程序中都很常见,你必须对值的变化做出反应,为了解决这个问题,我刚刚创建了一个特殊的钩子,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]
);
谢谢,让我知道,如果这不是你期望的建议,我会移动它。