简体   繁体   中英

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

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 = ...

Instead of setting socket as a state, you can try using 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>
      )
  }
}

Don't set a state object directly. Set it with setState({}).

  componentDidMount() {
    // io() not io.connect()
    const socket = io('http://localhost:9000');

    socket.on('queue', (queue) => {
      this.setState({
        queue,
      });
    });
    socket.open();

    this.setState({ socket });
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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