【问题标题】:Axios cancel token cancelling every requestaxios取消令牌取消每个请求
【发布时间】:2023-04-05 03:35:01
【问题描述】:

我正在尝试实现 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()
    }

【问题讨论】:

    标签: reactjs axios cancellationtokensource cancellation-token request-cancelling


    【解决方案1】:

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

    【讨论】:

    • 你提到了去抖动功能,我想知道它不会减慢用户体验吗?获取结果已经需要一些时间,我认为增加一些延迟只会减慢整个过程?
    • 确实会稍微延迟响应,但同时这将防止不必要的网络和后端活动。你只需要找到正确的妥协。我通常将我的设置为 50 毫秒
    猜你喜欢
    • 2019-11-26
    • 2017-10-14
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 2020-06-23
    • 2019-04-27
    相关资源
    最近更新 更多