gpt4 book ai didi

javascript - 类型错误 : Cannot read property of undefined with web-sockets

转载 作者:行者123 更新时间:2023-12-01 02:23:46 27 4
gpt4 key购买 nike

使用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)

为什么我无法访问state里面componentDidMount()

最佳答案

赋予channel.bind函数掩盖了componentDidMount()this。使用arrow function相 react 该可以解决问题。

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

关于javascript - 类型错误 : Cannot read property of undefined with web-sockets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48981083/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com