Axios 取消令牌取消每个请求

Sum*_*air 4 request-cancelling cancellationtokensource reactjs cancellation-token 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()
    }
Run Code Online (Sandbox Code Playgroud)

Her*_*rab 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); });
Run Code Online (Sandbox Code Playgroud)