React Native Android 上的 WebSocket 提供了"undefined is not a function"



我正在尝试使用Network polyfill:在React Native Android应用程序中创建WebSocket连接

'use strict';
var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;
var wstest = React.createClass({
  componentDidMount: function() {
    var ws = new WebSocket('ws://localhost:8080');
    ws.on('connect', function() {
      console.log('connected');
    })
  },
  render: function() {
    return (
      // ... left out for brevity
    );
  }
});
var styles = StyleSheet.create({
  // ... left out for brevity
});
AppRegistry.registerComponent('wstest', () => wstest);

我得到以下错误:

undefined is not a function (evaluating 'ws.on('connect',function() { ...

重新加载JS错误日志

构建环境中是否有我需要设置或配置的东西才能正常工作?

刚刚遇到了同样的问题。Facebook在WS上的React Native文档似乎不正确。在WS上侦听消息的正确方法如下:

    var ws = new WebSocket(url);
    ws.onopen = (() => {
        console.log("connection opened.");
    });
    ws.onmessage = ((message) => {
        console.log(message.data);
    });
    ws.onerror = ((error) => {
        console.log(error.message);
    });
    ws.onclose = ((event) => {
        console.log(event.code, event.reason);
    });

相关内容

  • 没有找到相关文章

最新更新