Axios取消令牌取消每个请求。

3
我正在尝试实现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()
    }
1个回答

6
在进行新的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); });

你提到了去抖动函数,我在想这样做会不会减缓用户体验?因为获取结果已经需要一些时间,我认为添加延迟只会使整个过程变慢。 - Sumair
的确,这将会给响应增加轻微延迟,但同时也可以避免不必要的网络和后端活动。你只需要找到合适的平衡点。我通常将我的设置为50毫秒。 - HermitCrab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接