我的应用程序中有评论部分,我正在尝试使用 axios.post 请求添加新评论。
这是 (Sequelize,nodeJS) :let commentArrayNew=[]
app.post('/addComment/:id', (req, res) => {
commentArrayNew.push(req.body.comment)
Posts.update({
comment: commentArrayNew
},
{
where: {
id: req.params.id
}
}).then((post) => {
res.send(post)
}).catch((err) => {
console.log("err", err);
});
})
在我的前端,每当我发送请求时,它都会给我状态 200,但它没有在页面上呈现新项目。这是我的 FE 请求
axios.post(`http://localhost:4000/addComment/${id}`, {
comment: commentValue.value
})
.then((res) => {
window.location.reload();
const {comment} : any = res.data
if(commentValue) {
dispatch(actions.addComment({comment}))
}
console.log('--------location', location.state);
})
.catch((err) => {
toast.info("Server error")
console.log('--------err', err);
})
我正在使用 useLocation 从另一个组件发送状态: const grabCommentsFromLocation = () => {
if (location.state) {
let commentArray = location.state.post.items.comment
let listItems = commentArray.map((item: Object[]) => {return <p key={uuidv4()}>{item}</p>})
return listItems
}
}
这是我渲染我的项目的地方:<div>
<p>Comment : </p>
{grabCommentsFromLocation()}
</div>
这是我来自 redux 的 dispatch 函数:export const addComment = (payload : any) => {
return {
type: actionTypes.ADD_COMMENT,
payload
}
}
case actionTypes.ADD_COMMENT:
return {
...state,
posts : [
...posts,
{
comment : action.payload.comment,
}
]
}
即使评论保存到数据库中,项目仍然没有显示,有什么建议吗?
最佳答案
你必须使用 res.status(200).json(post);相反 res.send(post)
关于node.js - POST 请求 ReactJS 后列表项未呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62773706/