javascript 如何防止在React中使用useEffect()进行无限次重新渲染?

im9ewurl  于 2023-01-11  发布在  Java
关注(0)|答案(1)|浏览(226)

我是新开发人员。我使用socket io创建了一个聊天应用程序。我只有在socket更改时才会更改useEffect,但我在useEffect()的主体中设置了setMessage,意思是更新消息,并将socket作为依赖项。但这不起作用,它会无限次地重新运行。

import React from 'react';
import ScrollToBottom from 'react-scroll-to-bottom';
import { useState,useEffect } from 'react';

function Chat({socket,username,room}) {
    const [currentMessage, setCurrentMessage] = useState("");
    const [messageList, setMessageList] = useState([]);
    const sendMessage = async () => {
        if (currentMessage !== "") {
            const messageData = {
                room: room,
                author: username,
                message: currentMessage,
                time: new Date(Date.now()).getHours()
                    + ':' +
                    new Date(Date.now()).getMinutes()
            };
            await socket.emit("send_message", messageData);
            sendMessage((list)=>[...list,messageData]);
            
        }
    };
    useEffect(() => {
        socket.on("receive_message", (data) => {
          setMessageList((list) => [...list, data]);
          setCurrentMessage("");
          
        });
      }, [socket]);
    return (
        <div className='chat-window'>
            <div className='chat-header'>
                <p>Live Chat</p>
            </div>
            <div className='chat-body'>
                <ScrollToBottom className='message-container'>
                {messageList.map((messageContent)=>{
                    return (
                    <div className='message' id={username===messageContent.author?"you":"other"}>
                       <h1>{messageContent.message}</h1>
                    </div>
                    );
                
                    })}
                </ScrollToBottom>

            </div>
            <div className='chat-footer'>
                <input type="text" value={currentMessage}placeholder='Hey..' onChange={(event) => {
                    setCurrentMessage(event.target.value);
                }} 
                onKeyPress={(event)=>{
                    event.key==='Enter'&&sendMessage();
                }}/>
                <button onClick={sendMessage}>&#9658;</button>
            </div>
        </div>
    );
}
export default Chat;

如何停止呈现useEffect函数?

qhhrdooz

qhhrdooz1#

为什么要将receive_message套接字侦听器传递给useEffect?是否尝试不使用useEffect

socket.on("receive_message", (data) => {
      setMessageList((list) => [...list, data]);
      setCurrentMessage("");
});

相关问题