繁体   English   中英

React js对象作为React子对象无效

[英]React js Objects are not valid as a React child

我正在尝试通过前端与后端建立套接字连接,但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 = ...直接设置状态

您可以尝试使用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>
      )
  }
}

不要直接设置状态对象。 使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM