要求 我有这个getValidationSchema`函数。我的任务需要将调用它的函数转换为对象的映射。
类似validationSchema[EDIT_INFO] = someSchema
,并使用我所有的映射而不是函数进行调用。
export const validationSchemas = {
ADD_USER: Yup.object().shape({
username: Yup.string('Provide a username').required('Username is required'),
email: Yup.string().email('Provide a valid email address'),
password: Yup.string('Provide a password').required('Password is required'),
confirmPassword: Yup.string('Provide your password again')
.required('Password confirmation is required')
.oneOf([Yup.ref('password')], 'Passwords do not match'),
group: Yup.string('Please select a group').required('Group is required')
}),
EDIT_INFO: Yup.object().shape({
username: Yup.string('Provide a username').required('Username is required'),
email: Yup.string().email('Provide a valid email address'),
group: Yup.string('Please select a group').required('Group is required')
}),
EDIT_PASSWORD: Yup.object().shape({
password: Yup.string('Provide a password').required('Password is required'),
confirmPassword: Yup.string('Provide your password again')
.required('Password confirmation is required')
.oneOf([Yup.ref('password')], 'Passwords do not match')
})
};
这是我到目前为止所拥有的功能:
const { mode } = this.props;
if (mode === ActionMode.EDIT_INFO) {
return validationSchemas.EDIT_INFO;
}
if (mode === ActionMode.EDIT_PASSWORD) {
return validationSchemas.EDIT_PASSWORD;
}
return validationSchemas.ADD_USER;
};
这是到目前为止我如何调用该函数。
validationSchema={this.getValidationSchemas}
这是我到目前为止所做的:
const mapValidationSchema: any;
validationSchemas[(validationSchemas.EDIT_PASSWORD, validationSchemas.EDIT_INFO,
validationSchemas.ADD_USER)] = this.mapValidationSchema;
validationSchema = {this.mapValidationSchema}
我显然做错了,因为出现多个错误并且表单验证不起作用。请注意,该表单位于React和TS中。
也有人要求我这样做,但是您能否向我解释为什么它比带有if语句的函数更好?除了看上去更干净以外,我想我对此没有任何好处。