reactjs - axios取消令牌取消每个请求
问题描述
我正在尝试实现 cancelToken API,以便每当我向服务器发出请求以获取每次击键的结果时,只有最后一个请求应该得到处理,但是我已经实现了 axios 取消令牌 API,它似乎取消了每个请求,我在这里做错了什么?每次击键都会调用此函数。
getProductLists2 = async () => {
let formData = new FormData()
const { start, limit } = this.state
formData.append('start', start)
formData.append('limit', limit)
formData.append('product_title', this.state.searchTitle)
formData.append('product_sku', this.state.searchSKU)
let cancel;
Axios({
method: 'POST',
url: BASE_URL + '/listProduct',
// headers: { 'Content-Type': 'multipart/form-data' },
data: formData,
cancelToken: new Axios.CancelToken(c => cancel = c)
})
.then(products => {
if (products && products.data.productList && products.data.productList.length > 0) {
this.setState({ productList: products.data.productList, totalProducts: products.data.productTotal })
}
})
.catch(err => toast.error('Something went wrong'))
console.log(cancel, 'h')
cancel && cancel()
}
解决方案
您应该在进行新的 axios 调用之前取消之前的 cancelToken。当你第一次请求时,保存 cancelToken。然后当你发出第二个请求时,检查是否已经存在 cancelToken 并取消它,然后进行第二个 axios 调用。
对 getProductLists2 进行去抖动以限制调用率也可能是一个好主意
我就是这样做的:
// Cancel the previous axios token if any
if (this.cancel) this.cancel.cancel();
// Get a new token
this.cancel = axios.CancelToken.source();
axios
.get(myURL, { cancelToken: this.cancel.token })
.then((res) => {
console.log(res.data);
})
.catch((error) => { console.log(error); });
推荐阅读
- null - 有没有办法将 PowerBI/Power Query 中日期数据类型列中的空值转换为空白?
- php - php artisan storage:使用 Laravel 和 Docker 时的链接问题
- amazon-dynamodb - 估计通过 Data Pipeline 导出 DynamoDB 数据的持续时间
- java - 显示为混合分数输入的值时出错
- swift - 根据函数的输出分配变量字符串值
- cmake - 在使用 CMake 安装期间创建指向不同文件夹中库的符号链接
- jsf - Apache Shiro 使用“unauthorizedUrl”
- json - 如何查找是否在 Liquid for Shopify 的字符串中找到单词?
- .net - 无法将 dotnet-sdk 升级到 5.0.200
- angular - Angular:检测父组件数据变化