首页 > 解决方案 > 在附加到反应挂钩 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


    }

标签: reactjssocket.io

解决方案


为了解决这个问题,我将下面的代码移到了 handlesubmit 函数中

const socket = io('http://localhost:3000');

推荐阅读