问题描述
我是react-formik的新手。我已经编写了使用react-formik进行简单表单提交的代码。但是,不幸的是,启动应用程序时出现类似 TypeError:无法读取未定义属性'email'的错误。我在下面共享了我的js代码供您参考。
需要注意的地方:
- 我仅创建了一个组件(LoginandSignup),并将此组件包含在我的App.js中
LoginandSignup.js
import React from 'react'
import {useFormik} from 'formik'
const initialValues={
email:'',firstname:'',lastname : '',password : ''
}
const onSubmit = values =>{
console.log('Formik values',values)
}
const validate = values =>{
let displayError={}
if(!values.email){
displayError.email='Email must not be empty'
}
else if(!/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/.test(values.email)){
displayError.email='Please enter the valid email address'
}
if(!values.firstname){
displayError.firstname='Please enter your first name'
}
if(!values.lastname){
displayError.lastname='Please enter your last name'
}
if(!values.password){
displayError.password='Please enter the password'
}
else if(!/^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{8,16}$/.test(values.password)){
displayError.password='Your password should contain more than 8 characters including one digit and one special character'
}
return displayError
}
function LoginandSignup(){
const formik = useFormik({
initialValues,onSubmit,validate
})
console.log('My Formik values',formik.values)
return(
<div>
<form onSubmit={formik.handleSubmit}>
<div className = 'form-control'>
<label htmlFor='email'>Email</label>
<input
type='email'
id='email'
name='email'
onChange={formik.handleChange}
value={formik.values.email}
/>
{formik.displayError.email ? (<div className='error'>{formik.displayError.email}</div>) : null}
</div>
<div className = 'form-control'>
<label htmlFor='firstname'>First Name</label>
<input
type='text'
id='firstname'
name='firstname'
onChange={formik.handleChange}
value={formik.values.firstname}>
</input>
{formik.displayError.firstname ? (<div className='error'>{formik.displayError.firstname}</div>) : null}
</div>
<div className = 'form-control'>
<label htmlFor='lastname'>Last Name</label>
<input
type='text'
id='lastname'
name='lastname'
onChange={formik.handleChange}
value={formik.values.lastname}>
</input>
{formik.displayError.lastname ? (<div className='error'>{formik.displayError.lastname}</div>) : null}
</div>
<div className = 'form-control'>
<label htmlFor='password'>Password</label>
<input
type='password'
id='password'
name='password'
onChange={formik.handleChange}
value={formik.values.password}>
</input>
{formik.displayError.password ? (<div className='error'>{formik.displayError.password}</div>) : null}
</div>
<button type='submit'>Submit</button>
</form>
</div>
)
}
export default LoginandSignup
Please find the error screenshot for your reference
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)