gpt4 book ai didi

reactjs - 在 useEffect 中访问 Formik 的 setValues

转载 作者:行者123 更新时间:2023-12-05 04:59:08 25 4
gpt4 key购买 nike

我有一个 Formik 表单需要响应错误 useContext。我不知道如何在 Form 之外访问 Formik 的 Prop 。我将在此处发布代码,如有任何建议,我将不胜感激。

  const authContext = useContext(AuthContext);
const { login, error, isAuth } = authContext;

useEffect(
() => {
if (isAuth) {
props.history.push("/");
}

if (error) {
// access Formik's setValues
}
},
// eslint-disable-next-line
[isAuth, error, props.history]
);

<Formik
initialValues={{
username: "",
email: "",
password: "",
password2: "",
}}
validationSchema={Yup.object({
email: Yup.string()
.email("Invalid email address.")
.required("An email is required."),
password: Yup.string().required("A password is required."),
})}
onSubmit={(submissionData, { setSubmitting }) => {
setSubmitting(true);
login(submissionData);
setSubmitting(false);
}}
>
{(props) => (
<Form>
<MyInput
label="Email: "
name="email"
type="email"
placeholder="Enter your email address"
/>
<MyInput
label="Password: "
name="password"
type="password"
placeholder="Enter your password"
/>
<button type="submit" className="btn">
{props.isSubmitting ? (
<ClipLoader size={16} color={"color"} />
) : (
"Submit"
)}
</button>
</Form>
)}
</Formik>

提前谢谢你。

最佳答案

您可以使用 useFormik Hook 来访问 setValues

您可以检查 docs here

例子:-

 import React from 'react';
import { useFormik } from 'formik';

export default function App() {
const formik = useFormik({
initialValues: {
firstName: '',
lastName: '',
email: '',
},
onSubmit: values => {
alert(JSON.stringify(values, null, 2));
},
});

React.useEffect(() => {
console.log(formik.setValues);
}, []);

return null;
}

关于reactjs - 在 useEffect 中访问 Formik 的 setValues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63637343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com