即使在渲染组件后,React 功能组件仍在更新最新数据

React function component is updating the latest data even after rendering the component

我创建了一个简单的应用程序来使用套接字构建消息传递应用程序。我面临的问题是,每当我从服务器收到有关消息的通知时,即使在渲染屏幕后消息数据也不会显示。你能帮我弄清楚为什么即使在渲染屏幕后它也没有更新新的消息长度吗?

//Updating socket object and initializing the state

  var socket = io("http://localhost:5000");
  const [message, setMessage] = useState('');
  const [messages, setMessages] = useState([]);

//Receive message from server 

  socket.on("server", (message) => {
    messages.push(message); 
    setMessages(messages); //Updating the state to re-render the screen - **does not render(Issue)**
  });

//Setting entered message on the screen - this renders fine

 const SetYourMessage = (event) => {
    event.preventDefault();
    setMessage(event.target.value);
  }

//On click on the button - screen render and update clear the the input field

 const callApi = (e) => {

    e.preventDefault();    
    socket.emit("chatMessage", message);
    setMessage('');
  }


**// Render part of the function component**

return (
    <div className="App"> 
      <header className="App-header">    
       {alert("Message length", messages.length)}   // This show the updated length
        <label>{messages.length}</label> **//Here updating the message length to check whether received the message or not (does not show thw updated value)**
        <input  value={message} onChange = {SetYourMessage} style={{border: '1px solid black', 
        outline:'none', backgroundColor: 'white', width:'300px', height: '30px'}}/>
        <button onClick={callApi}> Press Here</button>
      </header>
    </div>
  );
}

谢谢

你需要创建一个消息数组的新引用,否则 React 会认为数组是相同的,因为它有相同的引用

socket.on("server", (message) => {
  setMessages([...messages, message]);
});