javascript - React js 对象作为 React 子对象无效
问题描述
我正在尝试通过前端与后端建立套接字连接,但 sme 成功
我在我的状态下声明了我的套接字,然后打开了连接,但我不知道为什么会出现这个错误:
代码:
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 = ...
您socket
可以尝试使用this.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>
)
}
}
推荐阅读
- c++ - 为什么我们不能在 C++ 中初始化一个类的成员变量
- c# - 更新 X、Y、Z 浮点数和特定的 While 循环场景 C#
- java - 注册名为“dispatcher”的 servlet 失败。请检查是否有另一个以相同名称注册的 servlet。
- reactjs - CORS 标头“Access-Control-Allow-Origin”缺失 - Access-Control-Allow-Origin 已给出
- javafx - 为 Java 8 构建的 JavaFX 应用程序 - 如何继续使用 Java 11 运行?
- python - Python Tkinter - 不确定如何使用 messagebox.askretrycancel() 函数
- node.js - package-lock.json 中的 http 存储库依赖项
- r - 为什么 vecsets 包的 vunion 函数中的多个选项不适用于字符向量?
- r - 从R中的表达式对象中提取字符串
- yii2 - Yii2一页有多个ListView