【问题标题】:Why my code works with arrow function and broken with bind?为什么我的代码适用于箭头函数并被绑定破坏?
【发布时间】:2021-06-07 15:42:45
【问题描述】:

我认为bind(this) 相当于箭头函数但是我遇到了一个问题(

这是一个用于跟踪延迟请求的商店。我正在使用 orbitjs 库将所有​​内容保存到 IndexedDB 中。它提供了允许订阅数据库更改的 api,所以这里是我的商店:

export class DelayedRequestsStore implements IDelayedRequests {
    add = addHttpRequest;
    list = queryHttpRequests;
    remove = removeHttpRequest;

    @observable private _delayedRequestsCount = 0;

    @computed get any(): boolean {
        return this._delayedRequestsCount > 0;
    }

    @computed get empty(): boolean {
        return !this.any;
    }

    constructor(db: Sources) {
        db.source.on('update', () => {
            this._updateDelayedRequestsCount();
        });
        this._updateDelayedRequestsCount();
    }

    private async _updateDelayedRequestsCount(): Promise<void> {
        const delayedRequests = await this.list();
        runInAction(() => {
            this._delayedRequestsCount = delayedRequests.length;
        });
    }
}

查看构造函数上的代码

    constructor(db: Sources) {
        db.source.on('update', () => {
            this._updateDelayedRequestsCount();
        });
        this._updateDelayedRequestsCount();
    }

还有一些关于反应的代码:

<button onClick={async () => {
    await notifyServer(); 
    await clearRequestsFromIndexedDb();
    goToAnotherPage();
})>Cancel</button>

一切正常,直到我没有将构造函数代码更改为

    constructor(db: Sources) {
        db.source.on('update', this._updateDelayedRequestsCount.bind(this));
        this._updateDelayedRequestsCount();
    }

通过该更改,我在控制台中没有看到任何错误,但 Cancel 按钮不起作用。我调试过,发现notifyServer被调用了,然后clearRequestsFromIndexedDb被调用但是goToAnotherPage没有被调用,就像clearRequestsFromIndexedDb发生错误一样,但是没有错误。所以我回滚到箭头功能,一切都恢复正常了。它会影响什么吗?或者问题实际上在我错过的其他地方?

【问题讨论】:

  • 我认为“this”可能有问题,但不确定,除非我们得到一些工作代码

标签: javascript reactjs mobx orbit.js


【解决方案1】:

我看到你只绑定了thisdb.source.on('update', ... )。但是在构造函数中对 this._updateDelayedRequestsCount() 的调用没有绑定。这可能是个问题。

您可以像这样将this 显式绑定到您的每个方法调用:

constructor(db: Sources) {
    this._updateDelayedRequestsCount = this._updateDelayedRequestsCount.bind(this);
    
    db.source.on('update', this._updateDelayedRequestsCount);
        
    this._updateDelayedRequestsCount();
    }

也许它会解决你的问题。

【讨论】:

  • 将方法调用为this.foo() 可以正常工作,无需显式绑定任何内容。
  • @deceze 你是对的。我弄错了。谢谢和抱歉。
猜你喜欢
  • 2015-08-21
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 2017-09-25
相关资源
最近更新 更多