gpt4 book ai didi

reactjs - 通过 Formik 向服务器发送数据

转载 作者:行者123 更新时间:2023-12-04 07:53:06 26 4
gpt4 key购买 nike

我有 registerHandler 应该将数据发送到服务器。
在 Formik 我有 onSumbit

                    <Formik
initialValues={{
firstName: '',
lastName: '',
email: '',
password:''
}}
validationSchema={SignupSchema}
onSubmit={(
values: Values,
{setSubmitting}: FormikHelpers<Values>,
**const registerHandler** = async () => {
const authData = {
email:values.email,
password:values.password,
returnSecureToken:true
}
try {
const response = await axios.post('Link', authData)
console.log(response.data)
}catch (e){
console.log(e)
}
}

) => {
setTimeout(async () => {
setSubmitting(false);
}, 500);
}}
>
那里有一个看不到 registerHandler 的按钮
<button type="submit" className='settings-button' onClick={registerHandler}>Register</button>
如何正确传输到按钮 registerHandler?

最佳答案

可以绑定(bind)registerHandler功能与 onSubmit Formik 的 Prop :

const registerHandler = async (values, { setSubmitting }) => {
const payload = {
// make payload here using values
}
try {
const response = await axios.post('write_url_here', payload)
console.log(response.data)
} catch (e) {
console.log(e)
} finally {
setSubmitting(false)
}
}

// in render function's return

<Formik
initialValues={{
firstName: '',
lastName: '',
email: '',
password: '',
}}
onSubmit={registerHandler} // HERE
>
{(formik) => (
<form onSubmit={formik.handleSubmit}>

<label htmlFor="firstName">First Name</label>

<input id="firstName" type="text" {...formik.getFieldProps('firstName')} />

{formik.touched.firstName && formik.errors.firstName ? (
<div>{formik.errors.firstName}</div>
) : null}

<button type="submit" className='settings-button'>Register</button>

</form>
)}
</Formik>
请注意,您不需要将点击处理程序附加到 Register按钮,因为它的类型为 submit并且在 form 内.所以这个按钮会自动“提交”表单,即调用 onSubmitform这将触发 formik.handleSubmit最后触发函数 registerHandler .

关于reactjs - 通过 Formik 向服务器发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66851320/

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