本文介绍了ReactJS - this.functionname 不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 componentDidMount 中有一个监听器设置:

I have a listener setup in my componentDidMount:

updateBasketTotal: function() {
    BasketService.getBasketTotal(function(data){
        this.setState({
            selectedPeopleCount: data.TotalMembers
        });
    }.bind(this));
},

componentDidMount: function() {
    this.updateBasketTotal();
    this.subscribeToChannel(basketChannel,"selectAll",this.listenerSelectAll);
    this.subscribeToChannel(basketChannel,"removePersonFromBasket",this.listenerRemovePersonFromBasket);
    this.subscribeToChannel(basketChannel,"addPersonToBasket",this.listenerAddPersonToBasket);
    this.subscribeToChannel(basketChannel,"addArrayToBasket",this.listenerAddArrayToBasket);
},

listenerAddArrayToBasket: function(data){
    BasketService.addPerson(data.arrayToPush,function(){
        this.updateBasketTotal();
    });
},
listenerAddPersonToBasket: function(data){
    BasketService.addPerson(data.personId,function(){
        this.updateBasketTotal();
    });
},
listenerRemovePersonFromBasket: function(data){
    BasketService.removePerson(data.personId,function(){
       this.updateBasketTotal();
    });
},
listenerSelectAll: function(data){
    BasketService.selectAll(data.selectAll, function () {
        this.updateBasketTotal();
    });
}

但是,如果我不在此页面上发布消息,则会收到错误消息:

However, if I publish a message when I'm not on this page, I get an error:

this.updateBasketTotal 不是函数

谁能告诉我如何使用 this.updateBasketTotal?

Can anyone please tell me how I can use this.updateBasketTotal?

我认为这个"有问题,但不知道如何解决.提前致谢

I think its a problem with 'this' but not sure how to fix it. Thanks in advance

更新:

已尝试将 bind() 添加到侦听器:

Have tried adding bind() to the listener:

    listenerAddPersonToBasket: function(data){
    BasketService.addPerson(data.personId,function(){
        this.updateBasketTotal();
    }.bind());
},

但没有快乐,有什么想法吗?

But no joy, any ideas?

推荐答案

我假设您的组件正在取消订阅 componentWillUnmount 中的那些频道,以避免资源泄漏和重复订阅.

I assume your component is unsubscribing to those channels in componentWillUnmount to avoid resource leaks and duplicate subscriptions.

异步回调应调用 isMounted 以确保在尝试其他任何操作之前组件仍处于挂载状态.

The asynchronous callbacks should call isMounted to ensure the component is still mounted before attempting anything else.

BasketService.selectAll(data.selectAll, function () {
    if (this.isMounted()) {
        this.updateBasketTotal();
    }
}.bind(this));

我不知道 isMounted 检查是否会解决您的问题,因为这可能不再是一个函数.如果不是,您可以考虑添加自己的属性来跟踪组件是否已挂载并检查是否调用函数.

I don't know if the isMounted check will solve your problem since that may also not be a function anymore. If it isn't, you might consider adding your own property to track whether the component is mounted or not and check that rather calling a function.

这篇关于ReactJS - this.functionname 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 18:12