首页 > 解决方案 > 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,
                }
            ]

        }

即使评论保存到数据库中,项目仍然没有显示,有什么建议吗?

标签: node.jsreactjssequelize.js

解决方案


你必须使用 res.status(200).json(post); 而是 res.send(post)


推荐阅读