React状态没有更新

huangapple go评论72阅读模式
英文:

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) =&gt; {
const updatedChatList = chats.map(chat =&gt; {
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 = () =&gt; setEditMode(editMode =&gt; !editMode);
const deleteClick = () =&gt; {
fetch(`/topics/${topic.id}/chats/${id}`, {
method: &quot;DELETE&quot;,
})
deleteComment(id)
}
return (
&lt;div&gt;
&lt;ul&gt;
&lt;p&gt;&lt;strong&gt;{ chat.user.username }:&lt;/strong&gt; { chat.content }&lt;/p&gt;
&lt;/ul&gt;
{user &amp;&amp; user.username === chat.user.username &amp;&amp; (
&lt;div className=&quot;chat-btn&quot;&gt;
&lt;button className=&quot;delete-btn&quot; onClick={deleteClick}&gt;Delete&lt;/button&gt;
&lt;button className=&quot;edit-btn&quot; onClick={() =&gt; setEditMode(editMode =&gt; !editMode)}&gt;Edit&lt;/button&gt;
&lt;/div&gt;
)}
{ editMode &amp;&amp; &lt;ChatEdit chat={chat} topic={topic} editChat={editChat} editMode={editMode} setEditMode={setEditMode} /&gt; }
&lt;/div&gt;
)
}

ChatEdit.js

import { useState, useContext } from &quot;react&quot;;
import { ErrorsContext } from &quot;../context/ErrorsContext&quot;;
import Errors from &quot;../errors/Errors&quot;;
function ChatEdit({ chat, topic, editChat, editMode, setEditMode }) {
const { setErrors } = useContext(ErrorsContext);
const [content, setContent] = useState(chat.content);
const handleSubmit = (e) =&gt; {
e.preventDefault();
const editComment = {
content: content
}
fetch(`/topics/${topic.id}/chats/${chat.id}`, {
method: &quot;PATCH&quot;,
headers: { 
&quot;Accept&quot;: &quot;application/json&quot;,
&quot;Content-Type&quot;: &quot;application/json&quot; 
},
body: JSON.stringify(editComment)
})
.then(resp =&gt; resp.json())
.then(data =&gt; {
if (data.errors) {
setErrors(data.errors)
} else {
editChat(data)
setErrors([])
setEditMode(!editMode)
}
})
}
return (
&lt;form className=&quot;post-form&quot; onSubmit={handleSubmit}&gt;
&lt;div className=&quot;new-post&quot;&gt;
&lt;textarea className=&quot;chat-textarea&quot; type=&quot;text&quot; name=&quot;content&quot; placeholder=&quot;Write your comment.&quot; value={content} onChange={(e) =&gt; setContent(e.target.value)} /&gt;&lt;br/&gt;
&lt;button type=&quot;submit&quot;&gt;SEND&lt;/button&gt;
&lt;/div&gt;
&lt;Errors /&gt;
&lt;/form&gt;
)
}
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) =&gt; {
const updatedChatList = chats.map(chat =&gt; {
if (chat.id === newComment.id) { // Compare chat.id with newComment.id
return newComment;
} else {
return chat;
}
});
setChats(updatedChatList);
};

huangapple
  • 本文由 发表于 2023年6月22日 08:52:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528018.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定