[英]React js Objects are not valid as a React child
I am trying to make a socket connection to my backend through my front end, but sme successfully 我正在尝试通过前端与后端建立套接字连接,但sme成功
I declared my socket in my state and then opened the connection, but I don't know why this error: 我以我的状态声明了套接字,然后打开了连接,但是我不知道为什么会出现此错误:
code: 码:
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>
)
}
}
You should not set the state directly by using this.state.socket = ...
您不应该使用this.state.socket = ...
直接设置状态
Instead of setting socket
as a state, you can try using this.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>
)
}
}
Don't set a state object directly. 不要直接设置状态对象。 Set it with setState({}). 使用setState({})进行设置。
componentDidMount() {
// io() not io.connect()
const socket = io('http://localhost:9000');
socket.on('queue', (queue) => {
this.setState({
queue,
});
});
socket.open();
this.setState({ socket });
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.