【发布时间】: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