如何在Formik中集成提交函数对接Django API?
嘿,我看了你的代码,发现几个关键小问题导致提交逻辑可能出问题,咱们一步步来修正:
问题分析
- 参数顺序不匹配:你定义的
handleRegistration第一个参数是e,但在Formik的onSubmit里调用时传的第一个参数是values,这会导致e.preventDefault()报错,同时values也拿不到正确的数据。 - 函数组件不能用
this.props:Registration是函数组件,没法通过this.props.history获取路由对象,得用React Router的useHistory钩子。 - 多余的默认行为阻止:Formik的
onSubmit已经自动阻止了表单的默认提交行为,e.preventDefault()不仅多余,还会因为e不存在而抛出错误。
修正后的完整代码
// 先导入React Router的useHistory钩子 import { useHistory } from 'react-router-dom'; import { Formik } from 'formik'; const Registration = () => { // 获取路由history对象 const history = useHistory(); // 调整handleRegistration的参数,去掉不需要的e const handleRegistration = (values) => { fetch("http://127.0.0.1:8000/auth/users/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(values), }) .then((resp) => resp.json()) .then((res) => { console.log("registration res", res); // 用history.push代替window.location.href,更符合SPA路由逻辑 history.push("/login"); }) .catch((error) => { console.log("registration error", error); }); }; return ( <Formik initialValues={{ username: "", email: "", password: "", re_password: "", }} onSubmit={(values, { setSubmitting }) => { handleRegistration(values); setSubmitting(false); }} > {/* 这里放置你的表单字段,比如<Field name="username" />等组件 */} </Formik> ); };
额外提示
- 建议用
history.push代替window.location.href,这样不会刷新整个页面,更符合单页应用的交互逻辑。 - 如果遇到跨域请求错误,记得在Django端配置CORS(可以用
django-cors-headers包),否则浏览器会拦截请求。 - 可以根据后端返回的错误信息,在Formik里设置表单错误提示,提升用户体验。
内容的提问来源于stack exchange,提问作者Ewoma Zino
相关产品推荐
相关产品推荐

