reactjs - 在附加到反应挂钩 reactjs 和 socket.io 之前,消息会上下浮动
问题描述
我正在使用功能性反应钩子方法构建一个聊天消息应用程序,但是每次我发布消息时,消息都会刷新或上下浮动,然后才最终附加。如果使用类方法,一切正常。
这是类方法,可以正常工作并正常附加新的聊天消息
class App extends React.Component{
constructor(props){
super(props);
this.state = {
chats: [],
};
this.socket = io('http://localhost:3000');
this.socket.on('get_chat', function(msg){
this.setState({chats: [...this.state.chats, msg]});
});
this.handleSubmit = event => {
event.preventDefault();
socket.emit('post_chat', {
chat_message: 'helloworld message'
});
};
// render goes here
}
我的问题:
这是 ReactHook 功能方法,它在添加新聊天消息之前刷新或上下浮动,因此,一些消息被遗漏或替换。
我认为是这条线导致了问题
const socket = io('http://localhost:3000');
这是代码
import React, { Component, useState, useEffect, useRef } from "react";
import ReactDOM from 'react-dom';
import io from "socket.io-client";
const App = () => {
const [chats, setChats] = useState([]);
useEffect(() => {
// fetch content axio or ajax
}, []);
const socket = io('http://localhost:3000');
socket.on('get_chat', function(msg){
const newChats = chats;
setChats(newChats.concat([msg]));
});
function handleSubmit(event) {
event.preventDefault();
socket.emit('post_chat', {
chat_message: 'helloworld message'
});
};
//Return content goes here
}
解决方案
为了解决这个问题,我将下面的代码移到了 handlesubmit 函数中
const socket = io('http://localhost:3000');
推荐阅读
- python - 向量化结果/迭代模拟(在 python 中)
- javascript - Highcharts sunburst - 覆盖全局颜色
- sql - T-SQL - 将具有当前页面和以前页面的表转换为每个会话的顺序
- flutter - 我不能在堆栈中居中多个小部件
- gradle - 如何在 Gradle 中使用 pom 类型依赖
- amazon-web-services - Python 模块不在 AWS-EMR 的工作节点上
- octobercms - 当 OctoberCMS AJAX 调用 onSend 函数时,它不会执行它的代码
- qlikview - Qlik Sense:如何在 Google Drive 中指定路径?
- c# - MQTTnet 客户端无法连接服务器证书
- r - 在标题中插入图像并将其大小调整为字体大小