componentDidMount 中的 setState 不起作用

我发现其他帖子也有类似的错误,但那些帖子有需要绑定的功能。


在下面的简单程序中,我尝试在 AJAX 请求成功后更新 DOM,但出现错误“.TypeError:this.setState 不是函数”。请帮助我理解为什么这段代码不起作用。


import React from 'react';

import logo from './logo.svg';

import './App.css';



export class App extends React.Component {

    constructor(props) {

        super(props);

        this.state = {

            name: '(name will be inserted after ajax request)'

        };

        console.log('constructor');

    }



    componentDidMount() {

        //AJAX REQUEST

        const url = 'http://localhost:8080/ping';

        const xhr = new XMLHttpRequest();

        xhr.responseType = 'text';

        xhr.onreadystatechange = function() {

            if (xhr.readyState === XMLHttpRequest.DONE) {

                console.log(xhr.responseText);

                this.setState({name: xhr.responseText});

            }

        }

        xhr.open("GET", url);

        xhr.send();


    }




    render() {

        console.log('render')

        return <h1 > Hello {this.state.name} </h1>;

    }

}


偶然的你
浏览 175回答 3
3回答

慕尼黑的夜晚无繁华

尝试改变xhr.onreadystatechange&nbsp;=&nbsp;function()&nbsp;{到xhr.onreadystatechange&nbsp;=&nbsp;()&nbsp;=>&nbsp;{简短说明:内部thisafunction () {}取决于调用它的对象,因此当您将函数传递到某处时,您真的不知道this将引用什么。对于箭头函数,this指的this是封闭函数中的相同内容,即 for 的值this是词法解析的。您可以在此处阅读更详细的说明

蓝山帝景

将函数更改为箭头函数或将其作为函数中的参数传递,然后在函数中使用 this.setState({}) 像这样&nbsp; xhr.onreadystatechange = function(this) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (xhr.readyState === XMLHttpRequest.DONE) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(xhr.responseText);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.setState({name: xhr.responseText});&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }

慕斯709654

确保引用正确的对象或使用箭头函数componentDidMount() {&nbsp; &nbsp; &nbsp; &nbsp; //AJAX REQUEST&nbsp; &nbsp; &nbsp; &nbsp; var that = this;//make sure you reference the right object&nbsp; &nbsp; &nbsp; &nbsp; const url = 'http://localhost:8080/ping';&nbsp; &nbsp; &nbsp; &nbsp; const xhr = new XMLHttpRequest();&nbsp; &nbsp; &nbsp; &nbsp; xhr.responseType = 'text';&nbsp; &nbsp; &nbsp; &nbsp; xhr.onreadystatechange = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (xhr.readyState === XMLHttpRequest.DONE) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(xhr.responseText);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; that.setState({name: xhr.responseText});&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; xhr.open("GET", url);&nbsp; &nbsp; &nbsp; &nbsp; xhr.send();&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript