我正在开发一个 ReactJS 应用程序,我在其中实现了聊天屏幕。用户可以在文本区域中输入消息,然后单击“发送”按钮,消息将发送到后端 API。但是,在成功发布 API 后,我在更新前端聊天数组数据时遇到了问题。
这是我的 ReactJS 组件的简化版本:
<div className="textarea_sec">
<div className="btn_sec">
<textarea
value={this.state.chattext}
name="chattext"
onKeyPress={this.handleKeyPress}
onChange={this.handleChange}
placeholder="Enter your message.."
/>
<button
className="send-btn"
style={{ background: this.state.disable ? "grey" : null }}
disabled={this.state.disable}
onClick={() => {
this.sendMessage(this.state.chattext);
}}
>
Send
</button>
</div>
</div>
</div>
</div>
And here is the sendMessage function that handles the API post:
sendMessage = (message) => {
const data = {text:message};
axios
.post(BASEURL + "api/chat_post/", data, { headers })
.then((response) => {
if (response.data.status === 'success') {
this.setState({
chattext: "", // Emptying the textarea on successful post
});
}
this.getChatHistory();
this.scrollToBottom();
})
.catch((error) => {
toast("Post Chat API error" + error);
console.log("Post Message metrics axios error:", error);
});
};
即使聊天文本状态已成功重置,聊天数组 (this.getChatHistory()) 也不会按预期更新。我怀疑我更新状态或处理数组数据的方式可能存在问题。
有人可以提供有关如何确保在成功发布 API 后正确更新前端聊天数组的见解吗?
如果您对历史记录和
chattext
使用相同的状态 - 您可能会弄乱事情。因为你用 {chattext:''}
替换了之前的状态。
更新复杂状态的一般模式是:
newState = {...oldState, { chattext: ''}}
在这种情况下,您首先复制先前的状态,然后覆盖一些值。
第二个问题,如果您希望在状态更新后运行一些逻辑,您应该将其放入
useEffect
中,只需将以下内容移至 useEffect
部分并添加预计会影响它的依赖项。
this.getChatHistory();
this.scrollToBottom();