我创建了一个用户注册表单并通过使用formik
和yup
库向它添加验证。但问题是onSubmit
里面的方法<Formik>
不起作用。你能告诉我我的代码有什么问题吗?onSubmit
它应该在方法内传递输入值
该saveUser
方法是将输入值存储在mysql数据库表中
import React,{ useState } from 'react'
import { useHistory } from 'react-router-dom';
import { request, POST } from '../../../api/adapter';
import { Formik, Form, FormikProps} from 'formik';
import * as Yup from 'yup';
import {
Button,
TextField,
List,
ListItem,
ListItemText,
MenuItem,
Menu
} from '@material-ui/core';
interface ISignInForm {
username: string
password: string
email: string
}
interface IFormStatus {
message: string
type: string
}
interface IFormStatusProps {
[key: string]: IFormStatus
}
const formStatusProps: IFormStatusProps = {
success: {
message: 'Signed up successfully.',
type: 'success',
},
duplicate: {
message: 'Email-id already exist. Please use different email-id.',
type: 'error',
},
error: {
message: 'Something went wrong. Please try again.',
type: 'error',
},
}
export const FormRegister: React.FC = () => {
const [displayFormStatus, setDisplayFormStatus] = useState(false)
const [formStatus, setFormStatus] = useState<IFormStatus>({
message: '',
type: '',
})
const saveUser = async (data: ISignInForm, resetForm: Function) => {
try {
const result = await request(
`register`,
POST,
{
data,
userrole: selectedIndex,
},
);
console.log('Result: ' , result)
if (data) {
setFormStatus(formStatusProps.success)
resetForm({})
}
} catch (error) {
const response = error.response
if (
response.data === 'user already exist' &&
response.status === 400
) {
setFormStatus(formStatusProps.duplicate)
} else {
setFormStatus(formStatusProps.error)
}
} finally {
setDisplayFormStatus(true)
}
}
return(
<div className={classes.paper}>
<Formik
initialValues={{
username: '',
password: '',
email: '',
}}
onSubmit={(values: ISignInForm, actions) => {
console.log('Values:', values)
saveUser(values, actions.resetForm);
setTimeout(() => {actions.setSubmitting(false)}, 500);
}}
validationSchema={Yup.object().shape({
email: Yup.string()
.email()
.required('Enter valid email-id'),
username: Yup.string().required('Please enter username'),
password: Yup.string()
.matches(
/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*()]).{8,20}\S$/
)
.required(
'Please valid password. One uppercase, one lowercase, one special character and no spaces'
),
})}
>
{(props: FormikProps<ISignInForm>) => {
const {
values,
touched,
errors,
isSubmitting,
handleBlur,
handleChange,
handleSubmit
} = props
return (
<Form className={classes.form} onSubmit={handleSubmit}>
<TextField
variant="outlined"
name="email"
id="email"
label="Email Address"
value={values.email}
type="email"
margin="normal"
required
fullWidth
autoComplete="email"
autoFocus
helperText={errors.email && touched.email ? errors.email : 'Enter email address'}
error={errors.email && touched.email ? true : false}
onChange={handleChange}
onBlur={handleBlur}
/>
<TextField
type="text"
name="username"
id="username"
label="Username"
variant="outlined"
margin="normal"
required
fullWidth
autoComplete="username"
value={values.username}
helperText={
errors.username && touched.username
? errors.username
: 'Enter your username'
}
error={
errors.username && touched.username
? true
: false
}
onChange={handleChange}
onBlur={handleBlur}
/>
<TextField
variant="outlined"
name="password"
id="password"
label="Password"
value={values.password}
type="password"
margin="normal"
required
fullWidth
helperText={
errors.password && touched.password
? 'Please valid password. One uppercase, one lowercase, one special character and no spaces'
: 'One uppercase, one lowercase, one special character and no spaces'
}
error={
errors.password && touched.password
? true
: false
}
onChange={handleChange}
onBlur={handleBlur}
autoComplete="current-password"
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
disabled={isSubmitting}
onClick={() => {
selectedIndex === 1 ? history.push('/login/admin') : history.push('/login/employee')
}}
>
Sign Up
</Button>
{displayFormStatus && (
<div className="formStatus">
{formStatus.type === 'error' ? (
<p className={classes.errorMessage}>
{formStatus.message}
</p>
) : formStatus.type === 'success' ? (
<p className={classes.successMessage}>
{formStatus.message}
</p>
) : null}
</div>
)}
</Form>
)
}}
</Formik>
</div>
);
};