Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/383.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript undefined不是listView的对象(计算';this.state.ds';)_Javascript_React Native - Fatal编程技术网

Javascript undefined不是listView的对象(计算';this.state.ds';)

Javascript undefined不是listView的对象(计算';this.state.ds';),javascript,react-native,Javascript,React Native,我试图在react native中显示LISTVIEW中的元素 在本节中,我将尝试填充数据并检查行的相似性 并设置数据源。 构造函数(道具){ 超级(道具); this.socket=SocketIOClient('http://localHost:3000'); this.socket.on('Channel1',this.onReceivedMessage); var ds=新的ListView.DataSource({rowHasChanged:(r1,r2)=>r1!==r2}); 此.

我试图在react native中显示LISTVIEW中的元素

在本节中,我将尝试填充数据并检查行的相似性 并设置数据源。
构造函数(道具){
超级(道具);
this.socket=SocketIOClient('http://localHost:3000');
this.socket.on('Channel1',this.onReceivedMessage);
var ds=新的ListView.DataSource({rowHasChanged:(r1,r2)=>r1!==r2});
此.state={
ds:['rCode'],
数据源:ds
};
}

这是因为
onReceivedMessage
回调的上下文不是组件实例的上下文

因此,
this.state
未定义,因为
onReceivedMessage
是在全局/窗口上下文中执行的(即
this.state
未定义),而不是在组件实例的上下文中执行的

要从组件实例的上下文调用onReceivedMessage,请尝试将组件构造函数中的代码调整为:

constructor(props) {
    super(props);

    this.socket = SocketIOClient('http://localHost:3000');

    // Wrap the callback with a lambda function, so 
    // that onReceivedMessage is called from the context of your component
    this.socket.on('Channel1', (messages) => this.onReceivedMessage(messages));

    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      ds: ['rCode'],
      dataSource: ds

    };
  }
要更好地了解函数上下文和箭头函数的详细信息,请参见