我试图在表单中使用特定的字符串作为验证,但我得到了以下错误:
类型错误:无法读取未定义的属性"type">逻辑是管理员有一个他们只知道的特殊"magicword",它允许他们注册到系统,这是一种简单的方法,可以过滤出非管理员来注册
我附上了错误和沙盒链接,提前感谢!
49 | <div>
50 | <label htmlFor="magicword_field">Your Magic Word</label>
> 51 | <input type="text" id="magicword_field"
52 | ref={
53 | register({
54 | required: true,
https://codesandbox.io/s/exciting-bogdan-0z1bu?file=/src/App.js
import React from "react";
import axios from 'axios';
import {useForm} from "react-hook-form";
import './AdminSignup.css'
const AdminSignup = ({ setLoggedUser}) => {
const { register, handleSubmit , errors , watch} = useForm();
const onSubmit = (data) => {
console.log(data)
axios({
method:'POST',
url: 'http://127.0.0.1:5000/signup',
data: data
})
setLoggedUser(true)
.then(res => console.log(res))
.catch(err => console.error(err))
}
const passWord = watch('password')
return (
<div className = "wrap form-page">
<div className='nes-container with-title'>
<h2 className='title'>
Register Admin
</h2>
<br/>
<form onSubmit={handleSubmit(onSubmit)}>
<div>
<label htmlFor="name_field">Your name</label>
<input type="text" id="name_field" ref={register({required: '😱 forgot your name, old friend? 😱' })} name='name'/>
{errors.name && <p className='formError'>{errors.name.message}</p>}
</div>
<div>
<label htmlFor="email_field">Your email</label>
<input type="email" id="email_field" ref={register({ required: '📨 we prefer this over magic scrolls 📨', pattern: /^([a-zA-Z0-9_-.]+)@([a-zA-Z0-9_-.]+).([a-zA-Z]{2,5})$/})} name='email'/>
{errors.email && <p className='formError'>{errors.email.message}</p>}
</div>
<div>
<label htmlFor="password_field">Your Password</label>
<input type="password" id="password_field" ref={register({ required:'👹 no password? are you evena wizard?? 👹'})} name='password'/>
{errors.password && <p className='formError'>{errors.password.message}</p>}
</div>
{
passWord &&
<div>
<label htmlFor="magicword_field">Your Magic Word</label>
<input type="text" id="magicword_field"
ref={
register({
required: true,
validate: value => value === 'nerd'
},
)} name='magicword'/>
{errors.magicword.type === 'required' && <p className='formError'>
{'🔮 time to use it, just like they told you 🔮'}</p>}
{errors.magicword.type === 'validate' && <p className='formError'>
{'time to stop lying to yourself, buddy!'}</p>}
</div>
}
<br/>
<button className='b btn'>Register</button>
</form>
</div>
</div>
)
}
export default AdminSignup
我认为在访问errors.magicword.type
之前,您需要应用一些防御性编程步骤。只需使用!!
检查errors.magicword.type是否为undefined
。
{(!!errors.magicword.type) && (errors.magicword.type=== "required" && (
<p className="formError">
{"🔮 time to use it, just like they told you 🔮"}
</p>
))}