简体   繁体   English

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

[英]React function component is updating the latest data even after rendering the component

I have created a simple app to build a messaging app using socket.我创建了一个简单的应用程序来使用套接字构建消息传递应用程序。 The problem which I am facing is that whenever I receive the notification from the sever about the message, message does data does not display even after rendering the screen.我面临的问题是,每当我从服务器收到有关消息的通知时,即使在渲染屏幕后消息数据也不会显示。 Can you please help me to figure it out why its not updating the new message length even after rendering the screen.你能帮我弄清楚为什么即使在渲染屏幕后它也没有更新新的消息长度。

//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>
  );
}

Thanks谢谢

you will need to create a new reference of message array, otherwise React it will think that the array is the same since it has the same reference您将需要创建消息数组的新引用,否则 React 会认为该数组是相同的,因为它具有相同的引用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM