亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 252 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號