undefined不是listView ReactNative的对象(评估“ this.state.ds”)

时间:2018-07-18 22:07:29

标签: javascript react-native

我正在尝试以本机显示LISTVIEW中的元素

在本节中,我试图填充数据并检查行的相似性 并设置dataSource。

constructor(props) {
    super(props);
      this.socket = SocketIOClient('http://localHost:3000');
    this.socket.on('Channel1', this.onReceivedMessage);
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      ds: ['rCode'],
      dataSource: ds

    };
  }
  
  

在此处,rCode正确显示在listView中

  componentDidMount() {
  this.setState({
     dataSource:this.state.dataSource.cloneWithRows(this.state.ds),
    })

  }

在这里,我无法在listView中显示newD,这给了我错误

  onReceivedMessage(messages) {
    rcodeSet.add(JSON.stringify(messages.rCode));
    var newDs = [];

    newDs = Array.from(rcodeSet);

    this.setState({
        
        dataSource:this.state.ds.cloneWithRows([...newDs]),
      })
   }

错误:

undefined is not an object (evaluating 'this.state.ds')

1 个答案:

答案 0 :(得分:1)

这是因为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

    };
  }

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