我正在尝试更新帖子。后端的 PUT 请求工作正常,在 Postman 上测试时返回 200 并更新帖子,但是当我尝试更新前端的帖子( react )时,我没有收到任何错误,但更新的帖子没有被更新提交时更新,并且更新的字段(标题和正文)为空。当我在前端 console.log(data)
时,更新的值为空,这就是为什么它们不会发送到后端,但它们会在 post
中正确显示。
为什么更新后的值在 data
内为 null
?如何使用新值更新帖子而不是获取 null?
const EditPost = ({match}) => {
const [values, setValues] = useState({
title: "",
body: "",
error: ""
});
const [post, setPost] = useState({});
const { user, token } = isAuthenticated();
const {
title,
body,
error,
} = values;
const init = (id) => {
read(id).then(data => {
if (data.error) {
setValues({...values, error: data.error})
} else {
setValues({...values,
title: data.title,
body: data.body,
})
setPost({title: values.title, body: values.body})
}
})
}
useEffect(() => {
const id = match.params.id;
init(id);
}, []);
useEffect(() => {
setPost({...values });
}, [values.title, values.body]);
const handleChange = (name) => (event) => {
setValues({ ...values, [name]: event.target.value });
};
const clickSubmit = (event) => {
event.preventDefault();
setValues({ ...values, error: "" });
editPost(match.params.userId, match.params.id, token, post).then((data) => {
if (data.error) {
setValues({ ...values, error: data.error });
} else {
setValues({
...values,
title: "",
body: "",
error: false,
});
console.log(post)
console.log(data)
}
});
};
const newPostForm = () => (
<form onSubmit={clickSubmit}>
<div>
<input
onChange={handleChange("title")} type="text"
name="title"
value={title}
/>
</div>
<div className="form-group">
<textarea
onChange={handleChange("body")}
value={body} name="body"
/>
</div>
<button type="submit">Publish</button>
</form>
);
const showError = () => (
<div
style={{ display: error ? "" : "none" }}>
{error}
</div>
);
return (
<div>
{showError()}
{newPostForm()}
</div>
);
};
export default EditPost;
export const editPost = (userId, id, token, post) => {
return fetch(`${API}/${userId}/${id}/edit`, {
method: 'PUT',
headers: {
Accept: 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify(post)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
postsByUser.js
<Link className="mypost_btn edit_btn" to={`/${_id}/${post._id}/edit`}>
Edit
</Link>
后端代码
exports.edit = (req, res) => {
if (!ObjectID.isValid(req.params.id))
return res.status(400).send(`ID is not valid: ${req.params.id}`)
const {title, body} = req.body
const updatedPost = {title, body }
Post.findByIdAndUpdate(req.params.id, {
$set: updatedPost
}, {new:true}, (error, data) => {
if (error) {
return error
} else {
res.send(data)
console.log(data)
}
})
}
最佳答案
你的问题出在这里:
editPost(match.params.userId, match.params.id, token, post)
post
is not defined.
由于未定义 post
,因此不会传递任何数据。因此 title
和 body
等于 null
。从我在代码中看到的情况来看,您需要做的是定义一个名为 post
的状态变量。我认为您打算这样做:
const [post, setPost] = useState({values.title, values.body});
然后使用 useEffect()
确保您的帖子在您的值
发生变化时得到更新,
useEffect(() => {
setPost({...values });
}, [values.title, value.body]);
因此,当您调用 editPost()
http-put-method 时,post 就会有一个值
。它应该可以工作。
关于node.js - meern - 数据中更新的值为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63381633/