我一直在尝试通过验证制作一个简单的登录表单,然后提出了Formik和Yup。在编写验证之前,它只是一个功能组件,我很容易就使用了react-redux的useDispatch,但是在编写表单验证之后,我无法在组件内部使用react-redux,这给了我一个错误< / p>
React Hook "useDispatch" cannot be called inside a callback.
React Hooks must be called in a React function component or a custom React Hook function
我也知道我无法在回调中编写redux。作为新的React编码器,我找不到在相同组件中使用formik和redux的好解决方案。
这是我的没有redux的代码:
import React from 'react'
import { Link } from 'react-router-dom'
import { Formik } from 'formik'
import * as Yup from 'yup'
const Login = () => (
<Formik
initialValues={{ email: "", password: "" }}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
console.log("Logging in", values);
setSubmitting(false);
}, 1000);
}}
validationSchema={Yup.object().shape({
email: Yup.string()
.email("Email must be a valid email")
.required("Email required"),
password: Yup.string()
.required("No password provided.")
.min(8, "Is this really your PetsApp password?")
})}
>
{props => {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
handleBlur,
handleSubmit
} = props;
const defaultInputClassName = "shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
const errorInputClassName = "shadow appearance-none border border-red-500 rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
return (
<div>
<div className="w-full max-w-xs mx-auto pt-32">
<form onSubmit={handleSubmit} className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
<div className="mb-4">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="email">
Email
</label>
<input
className={errors.email && touched.email ? errorInputClassName : defaultInputClassName}
id="email"
type="text"
placeholder="email_address@your_mail.com"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
/>
{errors.email && touched.email &&
<p class="text-red-500 text-xs italic">{errors.email}</p>
}
</div>
<div className="mb-6">
<label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="password">
Password
</label>
<input className={errors.password && touched.password ? errorInputClassName : defaultInputClassName}
id="password"
type="password"
placeholder="******************"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
/>
{errors.password && touched.password &&
<p class="text-red-500 text-xs italic">{errors.password}</p>
}
</div>
<div className="flex items-center justify-between">
<button className="bg-purple-500 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
type="button"
disabled={isSubmitting}
>
Get In
</button>
<Link className="inline-block align-baseline font-bold text-sm text-purple-500 hover:text-purple-800" href="#">
Forgot Password?
</Link>
</div>
</form>
<p className="text-center text-gray-500 text-xs">
©2020 PetsApp. All rights reserved.
</p>
</div>
</div>
)}
}
</Formik>
)
export default Login
提交表单成功后,我需要调度login()操作。