使用表单onSubmit创建的数据未正确保存(React Hooks和JSON)



我有一个表单,它需要创建项"张贴";具有唯一的id、标题、作者和内容。类似这样的东西:

{
"posts": [
{
"id": 1,
"title": "First post",
"author": "Mathew",
"content": "This is a content"
},
{
"id": 2,
"title": "Second post",
"author": "Oliver",
"content": "This is a content 2"

问题是,当我提交一篇新帖子时,它被保存在json服务器中,如下所示:

{
"posts": [
{
"posts": {
"title": "First post",
"author": "Mathew",
"content": "This is content"
},
"id": 5
},
{
"posts": {
"title": "Second post",
"author": "Oliver",
"content": "This is content"
},
"id": 6
}
]
}

"id";在创建的元素之外;帖子";在父母之外";帖子";。这是我的代码:

形式:

const New: React.FC = () => {
// const [newPost, setNewPost] = useState("");
const [newPost, setNewPost] = useState({
title: '',
author: '',
content: ''
})
const handleInputChange = (e: React.FormEvent<HTMLInputElement>) => {
console.log((e.target as HTMLInputElement).value)
setNewPost({
...newPost,
[(e.target as HTMLInputElement).name]: (e.target as HTMLInputElement).value
})
};
const createPost = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault(); //Detiene el formulario para que no actualize la página
setPost(newPost)
}
return (
<div className="containerHomepage">
<form className="formulari" onSubmit={createPost}>
<div className="containerBreadCrumb">
<ul className="breadCrumb">
<li>Posts</li>
</ul>
</div>
<div className="containerTitleButton">
<input
className=""
type="text"
placeholder='Post title'
name="title"
onChange={handleInputChange}
></input>
<button
className="button"
type="submit"
>Save</button>
</div>
<div className="containerEdit">
<input
className=""
type="text"
placeholder='Author'
name="author"
onChange={handleInputChange}
></input>
<input
className=""
type="text"
placeholder='Content'
name="content"
onChange={handleInputChange}
></input>
</div>
</form>
</div>
);
};

// ========================================
export default New;

这里的函数setPost,创建一个新的帖子:

export function setPost(posts) {
return fetch('http://localhost:3004/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ posts })
})
.then(data => data.json())
}

我想这一定是代码中的一些小错误,但我不知道问题出在哪里。

将对象转换为JSON字符串时,将再次创建对象。

export function setPost(posts) {
return fetch('http://localhost:3004/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(posts) // Correction
})
.then(data => data.json())
}

最新更新