You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS中提交评论后如何实时获取并展示评论?

实现评论提交后无刷新实时展示的方案

要实现提交评论后无需刷新页面就能看到新评论,核心是在评论提交成功后直接更新前端维护的评论列表状态,而非依赖重新获取props。具体操作如下:

1. 将评论列表转为组件本地状态

当前你直接使用post.comment(来自props)渲染评论,无法直接更新。需要把评论列表放到组件的useState中,这样可以通过setState实时修改:

const PostWidget = ({ post }) => {
    const [loading, setLoading] = useState(false);
    const [show, setShow] = useState(false);
    const [commentInput, setComment] = useState({
        commentcontent: '',
    });
    // 新增:用本地状态维护评论列表,初始值取props中的post.comment
    const [comments, setComments] = useState(post.comment);
    const [errorlist, setError] = useState([]);

    const handleInput = (e) => {
        e.persist();
        setComment({ ...commentInput, [e.target.name]: e.target.value });
    }

    const submitComment = (e) => {
        e.preventDefault();
        setLoading(true);

        const data = {
            post_id: post.postid,
            commentcontent: commentInput.commentcontent,
        };

        axios.post(`/api/store-comment`, data).then((res) => {
            if (res.data.status === 200) {
                toast.success(res.data.message, "success");
                // 关键:把后端返回的新评论添加到列表最前面(或末尾,根据需求调整)
                // 确保后端返回完整的评论对象,包含渲染所需字段
                setComments(prev => [res.data.comment, ...prev]);
                // 清空输入框
                setComment({ commentcontent: '' });
                setLoading(false);
            }
            else if (res.data.status === 422) {
                toast.error("你的评论存在错误", "", "error");
                setError(res.data.errors);
                setLoading(false);
            }
        }).catch(() => {
            setLoading(false);
            toast.error("提交失败,请稍后重试");
        });
    }

    // ... 组件其余代码
}

2. 修改评论渲染逻辑

把原来用post.comment渲染的部分,改成用本地的comments状态,同时修正key值错误(之前用post.postid会导致所有评论key重复,React无法正确识别每个项):

{comments.map((comment) => {
    return (
        <div key={comment.id}> {/* 使用评论自身的唯一id作为key */}
            <div className="item"> {/* React中JSX需用className替代class */}
                <div className="avatar">
                    <img src="assets/img/sample/avatar/avatar1.jpg" alt="avatar" className="imaged w32 rounded" />
                </div>
                <div className="in">
                    <div className="singlecomment-header">
                        <h4 className="title">Diego Morata</h4>
                        <span className="time">just now</span>
                    </div>
                    <div className="text">
                        {comment.commentcontent}
                    </div>
                </div>
            </div>
        </div>
    )
})}

3. 后端配合要求

确保你的/api/store-comment接口在创建评论成功后,返回完整的新增评论数据(比如包含评论id、内容、用户信息等),这样前端才能直接把这个对象添加到评论列表中。

内容的提问来源于stack exchange,提问作者Oscar John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 22:25:23