简体   繁体   English

如何干燥此代码?

[英]How can I DRY up this code?

I want to iterate over the formProps object and check for the keys and set the value on the same keys onto the errors object. 我想遍历formProps对象并检查键,并将相同键上的值设置到errors对象上。

if (!formProps.email) {
    errors.email = "Please enter an email"
}
if (!formProps.password) {
  errors.password = "Please enter a password"
}
if (!formProps.passwordConfirm) {
  formProps.passwordConfirm = "Please enter a password confirmation"
}
if (formProps.password != formProps.passwordConfirm) {
  errors.password = "Passwords must match"
}

This will better as sending array because you can show all errors at same time 作为发送数组会更好,因为您可以同时显示所有错误

var errors = [];
!formProps.email ? errors.push("Please enter an email") : null;
!formProps.password ? errors.push("Please enter a password") : null;
!formProps.passwordConfirm ? errors.push("Please enter a password confirmation") : null;
formProps.password != formProps.passwordConfirm ? errors.push("Passwords must match") : null;
if(errors.length > 0){
    return errors;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM