我有一个Next.js应用程序,它为注册表单调用API。当服务器端出现验证错误时,我会得到如下响应:
{"message":"The given data was invalid.","errors":{"email":["The email has already been taken."],"password":["The password must be at least 8 characters."]}}
在我的代码中,我希望向用户显示email
和password
错误(如果它们存在的话)。目前我的代码是:
const RegisterPage: NextPageWithLayout = () => {
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
const [setEmailError, emailError] = useState<string | null>(null)
const [setPasswordError, passwordError] = useState<string | null>(null)
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (isSubmitting) return;
setIsSubmitting(true);
try {
// handle success
} catch (err){
// @ts-ignore
const errors = err?.response?.data?.errors;
if(errors instanceof Object){
setEmailError(errors['email']) // this does not work
setPasswordError(errors['password'] || null) // this does not work
}
setIsSubmitting(false);
}
};
然而,这段代码不起作用。我的IDE在设置电子邮件和密码错误的行上显示了几个错误:
TS2349: This expression is not callable.
Type 'String' has no call signatures.
TS2721: Cannot invoke an object which is possibly 'null'.
如何设置emailError
和passwordError
变量,以便在出现错误消息时向用户显示错误消息?
1条答案
按热度按时间nvbavucw1#
在
useState
中,Setter方法是第二个参数,而不是第一个参数。将类型添加到错误并检查错误是否为空