React Native Android上的WebSocket提供" undefined不是一个函数"

时间:2015-12-10 09:55:19

标签: android websocket react-native

我正在尝试使用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() { ...

Reload JS error log

构建环境中是否存在我需要设置或配置的内容才能生效?

1 个答案:

答案 0 :(得分:1)

刚遇到同样的问题。看来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);
    });