react-hook-form axios后无法创建负载



我使用react-hook-form, axios和功能组件将一些数据从浏览器输入表单发布到数据库中。然而,我只是不知道如何得到axios的基本方法。Post识别"输入表单数据"。表单是完全工作,我可以输入数据,可以看到浏览器控制台中有效的对象。但是我的请求有效载荷只是{}。

API端点也通过邮差进行测试。我也验证了后端是好的,因为我成功地测试了json对象(从邮差测试代码片段)直接从我的React脚本。只是我不知道如何把向axios.post表单输入数据。尽管在谷歌和youtube上花了几个小时,还是没能找到一个简单的答案!所以请帮忙!

抱歉,但我是一个绝对的新手编程和这是我的第一个帖子!因此,我不太可能理解技术上的答案,并要求您好心键入代码更改,如果您可以的话。我的代码如下:

import React from "react";
import {useForm} from "react-hook-form";
import axios from "axios";
function Eirform() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data) => console.log(data);
axios
.post('http://localhost:8000/tran', {onSubmit},
{headers: {'Content-Type': 'application/json',
},
})
.then(response => {console.log(response.data)})
.catch(error => {console.log(error.data)});
return (
<div>
<h1>My Input Form</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<input type="text" placeholder="Tran #" {...register("trn_no",{required: true})}/>
<input type="date" placeholder="Purchase date" {...register("pur_date",{required: "Required"})}/>
<input type="date" placeholder="Maturity date" {...register("mat_date",{required: "Required"})}/>
<input type="text" placeholder="Purchase Price" {...register("pur_pr",{required: "Required"})}/>
<input type="number" placeholder="Purchase Cost" {...register("pur_cost",{required: "Required"})}/>
<input type="text" placeholder="Coupon rate" {...register("cpn_rate",{required: "Required"})}/>
<input type="submit"/>
</form>
</div>
)
}
export {Eirform}

浏览器控制台图像

您需要将axios post放在提交函数本身中,以便它在那时执行。你现在拥有它的方式,它将在每次渲染时触发,并将失去data上下文,这就是为什么你看到一个空对象。

import React from "react";
import {useForm} from "react-hook-form";
import axios from "axios";
function Eirform() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = data => {
axios
.post(
'http://localhost:8000/tran',
data,
{ headers: { 'Content-Type': 'application/json' }}
)
.then(response => {console.log(response.data)})
.catch(error => {console.log(error.data)});
};
return (
<div>
<h1>My Input Form</h1>
<form onSubmit={handleSubmit(onSubmit)}>
...
</form>
</div>
)
}
export {Eirform}

相关内容