【问题标题】:intercepting XHR requests, javascript react拦截 XHR 请求,javascript 做出反应
【发布时间】:2018-09-17 18:02:32
【问题描述】:

我一直在尝试重写这些方法以拦截 xhr 请求,但似乎我所做的一切都只为 this.readyState 打印“1”。 有人知道为什么吗?

    addInterceptorsToXHRRequests() {
    const originalOpen = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function() {
        const originalStateChangeHandler = this.onreadystatechange;
        this.onreadystatechange = function() {
            console.log(' ---> ',this.readyState);
            if (originalStateChangeHandler instanceof Function) {
                originalStateChangeHandler.apply(this, arguments);
                console.log('Ready state: ' + this.readyState);
            }
        };
        return originalOpen.apply(this, arguments);
    };
}

我从 index.js 调用这个函数,在 componentDidMount 生命周期方法的末尾。 (相当大的项目)

【问题讨论】:

    标签: javascript reactjs xmlhttprequest


    【解决方案1】:

    这是因为您在 XMLHttpRequest.prototype.open 上绑定了一个函数。

    open 仅返回状态 1。 因此,您需要将 onreadystatechange 函数附加到完整的 xhr。

    示例

    // you probably want the original XMLHttpRequest here...
    const xhr = new XMLHttpRequest();
    
    xhr.onreadystatechange = function () {
       console.log(xhr.readyState);
    };
    

    【讨论】:

    • Jajajajajajajajaja.
    猜你喜欢
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 2010-11-21
    相关资源
    最近更新 更多