![](/img/trans.png)
[英]TypeError: Cannot read property '0' of undefined resolveModel react-redux-form
[英]REACT-FORM-HOOK TypeError: Cannot read property 'type' of undefined
我試圖在我的表單中使用特定字符串作為驗證,但出現此錯誤:
TypeError: Cannot read property 'type' of undefined邏輯是管理員有一個他們只知道的特殊“魔法詞”,它允許他們注冊到系統作為過濾掉非管理員注冊的簡單方法
我附上了錯誤和沙盒鏈接,在此先感謝!
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>
))}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.