英文:
React state isn't updating
问题
State isn't updating. I am trying to create the edit function to make edits on posted comments. When the submit button is clicked, nothing changes on the front end. After I refresh the page the changes appear. I can't seem to find where the problem is.
Content.js
// 处理编辑评论
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 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)}>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;
I am trying to get the edited comment to update once I submit the form. It's updating but not until I refresh the screen.
英文:
State isn't updating. I am trying to create the edit function to make edits on posted comments. When the submit button is clicked, nothing changes on the front end. After I refresh the page the changes appear. I can't seem to find where the problem is.
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;
I am trying to get the edited comment to update once I submit the form. It's updating but not until I refresh the screen.
答案1
得分: 0
在你的映射函数中,你正在将 topic.id 与 newComment.id 进行比较。应该是用 chat.id 来代替。
const editChat = (newComment) => {
  const updatedChatList = chats.map(chat => {
    if (chat.id === newComment.id) { // 将 chat.id 与 newComment.id 进行比较
      return newComment;
    } else {
      return chat;
    }
  });
  setChats(updatedChatList);
};
英文:
In your mapping function, you're comparing topic.id with newComment.id. It should be chat.id instead.
const editChat = (newComment) => {
const updatedChatList = chats.map(chat => {
if (chat.id === newComment.id) { // Compare chat.id with newComment.id
return newComment;
} else {
return chat;
}
});
setChats(updatedChatList);
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论