TypeError:无法使用web-socket读取undefined的属性

时间:2018-02-26 03:37:27

标签: javascript reactjs ecmascript-6 pusher isomorphic-javascript

使用Reom和pusher的Isomorphic框架来获取websockets。

当我进入componentDidMount()函数时,我似乎无法访问状态。

class TopbarNotification extends Component {
   state = {
     visible: false,
     notifications: []
   };

  constructor(props) {
    super(props);
    this.state = {
     notifications: [],
     visible: false
    };
  }

  componentDidMount() {
    var pusher = new Pusher('xxxxxxxxxxxx', {
       cluster: 'xxx',
       encrypted: true
    });

    var channel = pusher.subscribe('notifications');
    channel.bind('new-notification', function (data) {
      let newNotifications = this.state.notifications.push(data)
      this.setState({
        notifications: newNotifications
      })
      alert(data.message);
    });

  }

  render() {
     // ...Blah blah, blah blah
  }
}

我收到此错误:TypeError: Cannot read property 'notifications' of undefined

参考此行:let newNotifications = this.state.notifications.push(data)

为什么我无法访问state内的componentDidMount()

1 个答案:

答案 0 :(得分:1)

function的{​​{1}}使channel.bind的{​​{1}}黯然失色。使用arrow function代替应该做的。

this