如何将套接字响应设置为反应状态



每当套接字收到新数据时,我都会尝试将此数据设置为状态。
我正在创建简单的聊天应用程序,我想将从套接字集收到的最近聊天数据设置为状态。

var socket = constants.SERVER;  
var chatData = ""
class Chat extends Component {
constructor(props) {
super(props);
this.state = { recentChat:[] }
}

componentDidUpdate()
{
socket.on(constants.SOCKET_GET_CHAT, function(data){
console.log(JSON.stringify(data))
this.setState({
recentChat:data
})
});
}
render() {
return(<div/>)   
}
}
componentWillMount() {
socket.on(constants.SOCKET_GET_CHAT, (data) => {
this.setState({
recentChat:data
}) 
});
}

您必须在 componentWillMount 或 didMount 中附加侦听器。

socket.on(constants.SOCKET_GET_CHAT, data => {
this.setState(previousState => ({
recentChat: [...previousState.recentChat, data]
}))
});

您需要这样做,因为您将不断收到来自套接字的新消息,并且希望将聊天保留在此.state.recentChat中并附加新的聊天。

最新更新