Async/Await 与 Formik?
Async/Await with Formik?
我正在使用 formik,我想知道如何将 async/await 与 onSubmit
一起使用
<Formik
initialValues={{ email: '' }}
onSubmit={(values, { setSubmitting }) => {
// how to do async/await here.
}}
validationSchema={Yup.object().shape({
email: Yup.string()
.email()
.required('Required'),
})}
>
{props => {
const {
values,
touched,
errors,
dirty,
isSubmitting,
handleChange,
handleBlur,
handleSubmit,
handleReset,
} = props;
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email" style={{ display: 'block' }}>
Email
</label>
<input
id="email"
placeholder="Enter your email"
type="text"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
className={
errors.email && touched.email ? 'text-input error' : 'text-input'
}
/>
{errors.email &&
touched.email && <div className="input-feedback">{errors.email}</div>}
<button
type="button"
className="outline"
onClick={handleReset}
disabled={!dirty || isSubmitting}
>
Reset
</button>
<button type="submit" disabled={isSubmitting}>
Submit
</button>
<DisplayFormikState {...props} />
</form>
);
}}
</Formik>
您正在寻找这样的东西吗?
onSubmit={ async (values, { setSubmitting }) => {
await ...
setSubmitting(false)
}}
作为替代方案,您也可以创建一个单独的函数。
async function _handleSubmit(values) {
await...
}
onSubmit={(values, { setSubmitting }) => {
_handleSubmit(values)
setSubmitting(false)
}}
我正在使用 formik,我想知道如何将 async/await 与 onSubmit
一起使用<Formik
initialValues={{ email: '' }}
onSubmit={(values, { setSubmitting }) => {
// how to do async/await here.
}}
validationSchema={Yup.object().shape({
email: Yup.string()
.email()
.required('Required'),
})}
>
{props => {
const {
values,
touched,
errors,
dirty,
isSubmitting,
handleChange,
handleBlur,
handleSubmit,
handleReset,
} = props;
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email" style={{ display: 'block' }}>
Email
</label>
<input
id="email"
placeholder="Enter your email"
type="text"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
className={
errors.email && touched.email ? 'text-input error' : 'text-input'
}
/>
{errors.email &&
touched.email && <div className="input-feedback">{errors.email}</div>}
<button
type="button"
className="outline"
onClick={handleReset}
disabled={!dirty || isSubmitting}
>
Reset
</button>
<button type="submit" disabled={isSubmitting}>
Submit
</button>
<DisplayFormikState {...props} />
</form>
);
}}
</Formik>
您正在寻找这样的东西吗?
onSubmit={ async (values, { setSubmitting }) => {
await ...
setSubmitting(false)
}}
作为替代方案,您也可以创建一个单独的函数。
async function _handleSubmit(values) {
await...
}
onSubmit={(values, { setSubmitting }) => {
_handleSubmit(values)
setSubmitting(false)
}}