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

React State未实时更新:评论编辑提交后前端不刷新问题排查

问题:评论编辑提交后前端无法实时更新,刷新才生效

开发评论编辑功能时,点击提交按钮后前端界面无任何变化,但刷新页面后修改内容会正常显示。

相关代码

Content.js

// handle edit comments
const editChat = (newComment) => {
    const updatedChatList = chats.map(chat => {
        if (topic.id === newComment.id) {
            return newComment
        } else {
            return chat;
        }
    });
    setChats(updatedChatList);
}

ChatCard.js

function ChatCard({ chat, topic, deleteComment, editChat }) {
    const { user } = useContext(UserContext);
    const { id } = chat;
    const [editMode, setEditMode] = useState(false);
    // const openEditMode = () => setEditMode(editMode => !editMode);

    const deleteClick = () => {
        fetch(`/topics/${topic.id}/chats/${id}`, {
            method: "DELETE",
        })
        deleteComment(id)
    }

    return (
        <div>
            <ul>
                <p><strong>{ chat.user.username }:</strong> { chat.content }</p>
            </ul>
            {user && user.username === chat.user.username && (
                <div className="chat-btn">
                <button className="delete-btn" onClick={deleteClick}>Delete</button>
                <button className="edit-btn" onClick={() => setEditMode(editMode => !editMode)}>Edit</button>
                </div>
            )}
            { editMode && <ChatEdit chat={chat} topic={topic} editChat={editChat} editMode={editMode} setEditMode={setEditMode} /> }
        </div>
    )
}

ChatEdit.js

import { useState, useContext } from "react";
import { ErrorsContext } from "../context/ErrorsContext";
import Errors from "../errors/Errors";

function ChatEdit({ chat, topic, editChat, editMode, setEditMode }) {
    const { setErrors } = useContext(ErrorsContext);
    const [content, setContent] = useState(chat.content);

    const handleSubmit = (e) => {
        e.preventDefault();
        const editComment = {
            content: content
        }
        fetch(`/topics/${topic.id}/chats/${chat.id}`, {
            method: "PATCH",
            headers: { 
                "Accept": "application/json",
                "Content-Type": "application/json" 
            },
            body: JSON.stringify(editComment)
        })
        .then(resp => resp.json())
        .then(data => {
            if (data.errors) {
                setErrors(data.errors)
            } else {
                editChat(data)
                setErrors([])
                setEditMode(!editMode)
            }
        })
    }

    return (
        <form className="post-form" onSubmit={handleSubmit}>
            <div className="new-post">
            <textarea className="chat-textarea" type="text" name="content" placeholder="Write your comment." value={content} onChange={(e) => setContent(e.target.value)} /><br/>
            <button type="submit">SEND</button>
            </div>
            <Errors />
        </form>
    )
}

export default ChatEdit;

问题原因与修复

问题出在Content.js的editChat函数中,判断匹配评论的条件错误:
原代码用topic.id(话题ID)和newComment.id(评论ID)做比较,完全无法匹配到目标评论,导致chats数组没有被正确更新,前端自然不会触发重渲染。

将判断条件修正为用评论自身的ID匹配:

const editChat = (newComment) => {
    const updatedChatList = chats.map(chat => {
        // 修正:使用评论ID匹配目标评论
        if (chat.id === newComment.id) {
            return newComment
        } else {
            return chat;
        }
    });
    setChats(updatedChatList);
}

修改后,提交编辑请求后,chats数组会正确替换为修改后的评论数据,前端就能实时更新显示内容了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 06:10:45