我正在尝试通过前端与后端建立套接字连接,但成功了
我在我的状态中声明了我的套接字,然后打开了连接,但我不知道为什么会出现此错误:
代码:
class App extends Component {
constructor(props, context){
super(props, context);
this.state = {
queue: '',
socket: null
};
}
componentDidMount() {
// io() not io.connect()
this.state.socket = io('http://localhost:9000');
this.state.socket.on('queue', (queue) => {
this.setState({
queue
})
});
this.state.socket.open();
}
componentWillUnmount() {
this.state.socket.close();
}
render() {
return (
<div>
<p> Queue: {this.state.queue} </p>
</div>
)
}
}
最佳答案
您不应使用 this.state.socket = ...
直接设置状态
您可以尝试使用 this.socket
,而不是将 socket
设置为状态。
class App extends Component {
constructor(props, context){
super(props, context);
this.socket = null;
this.state = {
queue: '',
};
}
componentDidMount() {
// io() not io.connect()
this.socket = io('http://localhost:9000');
this.socket.on('queue', (queue) => {
this.setState({
queue: queue
})
});
this.socket.open();
}
componentWillUnmount() {
this.socket.close();
}
render() {
return (
<div>
<p> Queue: {this.state.queue} </p>
</div>
)
}
}
关于javascript - React js 对象作为 React 子对象无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59042414/