我有一個表單,它需要創建具有唯一 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”在創建的元素之外,“posts”在父“posts”之外。這是我的代碼:
形式:
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())
}
我想這一定是代碼中的一些小錯誤,但我不知道是什么問題。
uj5u.com熱心網友回復:
將物件轉換為 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())
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/429453.html
