首页 > 解决方案 > 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>
        )
    }
}

标签: javascriptreactjs

解决方案


您不应该使用直接设置状态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>
      )
  }
}

推荐阅读