【发布时间】:2019-01-27 17:02:19
【问题描述】:
当用户停止输入时我必须调用 API 并且它工作得非常好。当按下回车键时我必须安装。 我做了一个Mock Component here 来做这个。
但是,当组件被卸载时,它会显示错误Cannot call setState on an unmounted component。以前我用this.isMounted 处理了这个错误。现在,我尝试使用 React Blog 中提到的 componentWillUnmount 中的承诺取消来处理它。
this.cancellablePromise = makeCancelable(getSearchResults(word));
this.cancellablePromise.promise
.then(res => {
console.log({ res });
this.setState({ values: res });
})
.catch(err => console.log("error", err));
console.log("in data ", this.cancellablePromise);
}
cancellablePromise 在 promise 得到解决后被分配。所以在 componentWillUnMount 中有一个 null 对象用于cancellablePromise 实例。
【问题讨论】:
-
makeCancelable到底是做什么的? -
你应该看看像github.com/slorber/awesome-debounce-promise这样的基于promise的去抖动。正如这里所解释的,可观察对象更适合此类任务,stackoverflow.com/a/54328220/3731501。使用 RxJS
debounce很容易。 -
如果我们跟踪所有承诺并取消它,它就会起作用......
-
@estus 谢谢你,我会看看它
-
现在工作正常