【问题标题】:React function component is updating the latest data even after rendering the component即使在渲染组件之后,React 函数组件也会更新最新数据
【发布时间】:2021-05-29 15:56:43
【问题描述】:

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

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

谢谢

【问题讨论】:

    标签: javascript reactjs socket.io


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-02-18
      • 1970-01-01
      • 2017-12-29
      • 2022-01-19
      • 1970-01-01
      • 2022-11-04
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多