【发布时间】: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