【发布时间】:2022-01-28 07:13:51
【问题描述】:
我正在尝试创建一个从接受来自字段的用户输入的表单调用的发布请求,但发布请求需要特定的数据格式并且具有如下嵌套的部分:
{
"Product": {
"name": "App1",
"version": "1.0.0",
"location": "C:\app1"
},
"Owner": {
"name": "John Smith",
"email": "john@smith.com"
},
"Clients": [
{
"name": "client1",
"location": {"address": "123 Jon street", "contact_number": "123456789"}
},
{
"name": "client2",
"location": {"address": "123 Jon street", "contact_number": "123456789"}
}
]
}
除了客户列表之外的所有内容都来自表单中的用户输入。 我的 app.js 在下面
import React, {useState} from 'react';
import { useForm } from 'react-hook-form';
import clients from './components/clients';
import axios from "axios";
export default function App() {
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = data => {
axios
.post('/api/product',
data,
{ headers: { 'Content-Type': 'application/json' }}
)
.then(response => {console.log(response.data)})
.catch(error => {console.log(error.data)});
};
//const onSubmit = data => console.log(data);
return (
<div>
<h3>Client listing</h3>
<clients />
<h3>Owner Details</h3>
<form onSubmit={handleSubmit(onSubmit)}>
<label>Owner name: </label><input type="text" placeholder="Owner name" {...register("Ownernane", { required: "Invalid Entry", maxLength: 80 }) } /><p>{errors.Ownernane?.message}</p>
<label>EMail: </label><input type="text" placeholder="Email" {...register("Email", { required: "Invalid Entry", pattern: /^\S+@\S+$/i }) } /><p>{errors.Email?.message}</p>
<h3>Product details</h3>
<label>Name: </label><input type="text" placeholder="name" {...register("name", { required: "Invalid Entry", maxLength: 80 }) } /><p>{errors.name?.message}</p>
<label>Location: </label><input type="text" placeholder="location" {...register("location", { required: "Invalid Entry", maxLength: 100 }) } /><p>{errors.location?.message}</p>
<label>Version: </label><input type="text" placeholder="version" {...register("version", { required: "Invalid Entry", maxLength: 12 }) } /><p>{errors.version?.message}</p>
<input type="submit" />
</form>
</div>
);
}
有人可以为我指出如何做到这一点的正确方向吗?我不确定它是否是我使用的术语,但我很难找到这方面的说明,并猜测这是一个很常见的处理方式。非常感谢。
【问题讨论】:
标签: reactjs axios react-hook-form