我正在尝试使用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() { ...
构建环境中是否存在我需要设置或配置的内容才能生效?
答案 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);
});