node.js - POST 请求 ReactJS 后列表项未呈现
问题描述
我的应用中有评论部分,我正在尝试使用 axios.post 请求添加新评论。
这是(续集,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 的调度函数:
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 - 将 cookie 发送回客户端
- dojo - 在 dojo BorderContainer 中设置中心窗格的最小尺寸
- flutter - Flutter textfield onChanged - 检测最后输入的文本是否是标签句柄'@mention'
- docker - 将 Docker Entrypoint 日志实时发送到 APP
- javascript - Vercel 现在服务器不适用于谷歌电子表格
- text - 从缓冲区中删除换行符(在导入 ORG 以在保留段落的同时展开文本时很有用)
- python - 通过搜索另一个数据框来映射新列的值
- tensorflow - .pb 和 .h5 之间的区别
- mysql - 在 Spring Boot 中编译 SQL 过程
- python - Python:从定义的属性列表中调用列表属性