Javascript undefined不是listView的对象(计算';this.state.ds';)
我试图在react native中显示LISTVIEW中的元素 在本节中,我将尝试填充数据并检查行的相似性 并设置数据源。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}); 此.
构造函数(道具){
超级(道具);
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
};
}
要更好地了解函数上下文和箭头函数的详细信息,请参见