使用异态框架进行React和Pusher获取Websocket。
当我在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)
为什么我不能在componentDidMount()
中访问state
?
channel.bind
给出的function
覆盖了componentDidMount()
的this
。使用箭头功能应该做到这一点。
channel.bind('new-notification', data => {
let newNotifications = this.state.notifications.push(data)
this.setState({
notifications: newNotifications
})
alert(data.message);
});
您可以测试以下内容:
componentDidMount() {
var pusher = new Pusher('xxxxxxxxxxxx', {
cluster: 'xxx',
encrypted: true
});
let _this = this;
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);
});
}