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

标签 javascript reactjs

我正在尝试通过前端与后端建立套接字连接,但成功了

我在我的状态中声明了我的套接字,然后打开了连接,但我不知道为什么会出现此错误:

代码:

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>
      )
  }
}

关于javascript - React js 对象作为 React 子对象无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59042414/

相关文章:

javascript - 使用 javascript 在表格单元格中插入数组值

javascript - 当函数执行 Jquery 时做一些事情

javascript - 在第 3 方(场外)购物车上使用 Google Analytics 进行转化跟踪

javascript - 如何管理 Node.js 异步变量作用域?

javascript - ReactJs 子组件未通过 Props 更新

javascript - 如何为数组中的相同字符串值生成永久的 React 键?

reactjs - 如何从 themoviedb 获取所有电影的数组?

javascript - 正则表达式匹配年份,但不匹配javascript中的其他数字

javascript - react Redux reducer : 'this.props.tasks.map is not a function' error

javascript - 将对象传递给 Router.push NextJs 上的查询