为了账号安全,请及时绑定邮箱和手机立即绑定

componentDidMount 中的 setState 不起作用

componentDidMount 中的 setState 不起作用

偶然的你 2023-01-06 15:19:42
我发现其他帖子也有类似的错误,但那些帖子有需要绑定的功能。在下面的简单程序中,我尝试在 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>;    }}
查看完整描述

3 回答

?
慕尼黑的夜晚无繁华

TA贡献1864条经验 获得超6个赞

尝试改变

xhr.onreadystatechange = function() {

xhr.onreadystatechange = () => {

简短说明:

内部thisafunction () {}取决于调用它的对象,因此当您将函数传递到某处时,您真的不知道this将引用什么。

对于箭头函数,this指的this是封闭函数中的相同内容,即 for 的值this是词法解析的。

您可以在此处阅读更详细的说明


查看完整回答
反对 回复 2023-01-06
?
蓝山帝景

TA贡献1843条经验 获得超7个赞

将函数更改为箭头函数或将其作为函数中的参数传递,然后在函数中使用 this.setState({}) 像这样


  xhr.onreadystatechange = function(this) {

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

            console.log(xhr.responseText);

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

        }

    }


查看完整回答
反对 回复 2023-01-06
?
慕斯709654

TA贡献1840条经验 获得超5个赞

确保引用正确的对象或使用箭头函数


componentDidMount() {

        //AJAX REQUEST

        var that = this;//make sure you reference the right object

        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);

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

            }

        }

        xhr.open("GET", url);

        xhr.send();


    }


查看完整回答
反对 回复 2023-01-06
  • 3 回答
  • 0 关注
  • 167 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信