gpt4 book ai didi

javascript - React js Socket.io 和 State

转载 作者:行者123 更新时间:2023-12-02 22:27:55 25 4
gpt4 key购买 nike

你好,我正在尝试保存我的套接字通过后端发送给我的响应的状态

这是我向套接字发送消息的方法

export default class Home extends Component { 

constructor(){
super()

this.state = {
informationReceived: 'Nothing yet!'
}
const token = localStorage.getItem('token');
const socket = io('http://localhost:8080', {
query: { token: token }
});

socket.on('success', (receivedInfo) => {
this.setState({
informationReceived: receivedInfo
})
})

}

emitInfoToAll = () => {
const token = localStorage.getItem('token');
console.log('entrou')
const socket = io('http://localhost:8080',{
query: { token: token }
});

socket.emit('myevent', 'Hello realtime connected users!')
console.log(this.state.informationReceived);
}
}

但是这样我会在发送和接收时两次打开与套接字的连接我想知道如何只能打开一个连接,这样当我向后端发送回复时,我就不必再次打开

我如何设置我的 p 标签的这些值:

                <p> Name: <span className = "name"> </span> </p>
<p> Points: <span className = "points"> 0 </span> </p>

最佳答案

您应该将 socket 放置为组件的状态,以便可以在 emitInfoToAll 方法中模拟它

export default class Home extends Component { 

constructor(){
super()

this.state = {
informationReceived: 'Nothing yet!'
socket: null;
}

const token = localStorage.getItem('token');
socket = io('http://localhost:8080', {
query: { token: token }
});

socket.on('success', (receivedInfo) => {
this.setState({
informationReceived: receivedInfo
})
})

}

emitInfoToAll = () => {
const { socket } = this.state;
console.log('entrou')
socket.emit('myevent', 'Hello realtime connected users!')
console.log(this.state.informationReceived);
}
}

更新:帮助设置 p 标记的值

export default class Home extends Component {

constructor() {
super()

this.state = {
informationReceived: 'Nothing yet!',
socket: null
}

const token = localStorage.getItem('token');
socket = io('http://localhost:8080', {
query: { token: token }
});

socket.on('success', (receivedInfo) => {
this.setState({
informationReceived: receivedInfo
})
})

}

emitInfoToAll = () => {
const { socket } = this.state;
console.log('entrou')
socket.emit('myevent', 'Hello realtime connected users!')
console.log(this.state.informationReceived);
}

render() {
const { informationReceived } = this.state;
const { name, point } = informationReceived;
return (
<div>
<p> Name: <span className="name">{name}</span> </p>
<p> Points: <span className="points">{point}</span> </p>
</div>
);
}
}

关于javascript - React js Socket.io 和 State,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58998179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com