Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ';这';引用React组件的XMLHttpRequest回调中的关键字_Javascript_Reactjs - Fatal编程技术网

Javascript ';这';引用React组件的XMLHttpRequest回调中的关键字

Javascript ';这';引用React组件的XMLHttpRequest回调中的关键字,javascript,reactjs,Javascript,Reactjs,我在React应用程序的XMLHttpRequest回调中遇到了一个“this”关键字问题。这里的目标是使用来自XML对象的响应更新组件状态。但是,在XML对象的回调函数中,“this”关键字指的是对象本身,而不是组件。我似乎无法逃脱这个惩罚 在这种情况下,如何引用组件以更新其状态 componentDidMount() { const xhr = new XMLHttpRequest(); xhr.withCredentials = false;

我在React应用程序的XMLHttpRequest回调中遇到了一个“this”关键字问题。这里的目标是使用来自XML对象的响应更新组件状态。但是,在XML对象的回调函数中,“this”关键字指的是对象本身,而不是组件。我似乎无法逃脱这个惩罚

在这种情况下,如何引用组件以更新其状态

componentDidMount() {

        const xhr = new XMLHttpRequest();
        xhr.withCredentials = false;

        xhr.addEventListener("readystatechange", function () {
            if (xhr.readyState === 4 && this.status == 200) {
                //in the line below I cannot access my component due to 'this' keyword refering to xhr.
                this.setState({ teams: JSON.parse(this.responseText).api.teams }); 
                console.log(this.state);
            }
        });

        xhr.open("GET", "https://api-football-v1.p.rapidapi.com/v2/teams/league/3097");
        xhr.setRequestHeader("x-rapidapi-key", "xxxxxx");
        xhr.setRequestHeader("x-rapidapi-host", "api-football-v1.p.rapidapi.com");
        xhr.send(null);
    }
OBS:我必须使用XMLHttpRequest来执行这个ajax请求。

更改

xhr.addEventListener("readystatechange", function () {});


这样回调函数就不会创建一个新的上下文,而不是函数(){}或函数(){}.bind(这个)谢谢TJ。这种语法有一个特定的名称吗?我记得以前使用过它,不知道它阻止JS创建另一个上下文。它被称为箭头函数
xhr.addEventListener("readystatechange", () => {})