React - 使用“this”上下文绑定pusher事件回调

时间:2017-07-11 08:14:06

标签: reactjs this bind

编辑:我已将其更新为使用for of但仍有同样的错误,无法访问handleEventState

我正在尝试动态订阅和绑定推送通道/事件。 在ComponentDidMount上,我调用API来获取可用的通道及其事件。在接收数据时,我订阅并绑定到这些事件。然而,通过

的错误,对事件绑定的回调函数
  

无法读取未定义

的属性'handleEventState'

任何人都可以看到这里的错误。

构造

constructor(props, context) {
super(props, context);

this.state = {
  site: null,
  iframe_url: null,
  channel_data: null,
};

this.bindData = this.bindData.bind(this);
this.handleEventState = this.handleEventState.bind(this);

}

ComponentDidMount:

  axios.get(url)
  .then(response => {
    const data = response.data;
    this.setState({channel_data: data});
    this.bindData();
  })
  .catch((error) => {
  console.log("error",error)
});

bindData:

      var pusher = new Pusher('8a8708c8544df5252f22', {
      cluster: 'eu',
      encrypted: true
    });
    // get the data from mapping api
   var data = this.state.channel_data.channels;
    // loop each channel and subscribe to each of its event
      for(let channels of data) {
        var channel = pusher.subscribe(channels.channel_name);
        var events = channels.events;
        // Inner loop to bind the pusher event with the channel
        for(let event of events ) {
          channel.bind(event, this.handleEventState);
        }
      }

0 个答案:

没有答案