第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

TypeError:無法讀取未定義的屬性“ setState”

TypeError:無法讀取未定義的屬性“ setState”

桃花長相依 2019-11-20 14:39:27
我試圖在ajax回調(diào)從REST api接收數(shù)據(jù)后設(shè)置組件的setState。這是我的組件構(gòu)造函數(shù)代碼constructor(props) {    super(props);    this.state = { posts: [] };    this.getPosts = this.getPosts.bind(this);}然后,我有一個componentDidMount如下所示的方法。componentDidMount() {        this.getPosts();}現(xiàn)在,這是我執(zhí)行g(shù)etAJAX請求的getPosts函數(shù)。getPosts = () =>  {    $.ajax({        type: 'get',        url: urlname,        success: function(data) {            this.setState( { posts: data } )        }    });}我想設(shè)置狀態(tài),但出現(xiàn)以下錯誤。this.setState is not a function不太清楚是什么原因造成的。如果有人指出我正確的方向,那將非常有幫助。提前致謝。
查看完整描述

3 回答

?
繁星淼淼

TA貢獻(xiàn)1775條經(jīng)驗 獲得超11個贊

還綁定回調(diào)函數(shù),以便this回調(diào)內(nèi)部指向React Component的上下文,而不是回調(diào)函數(shù)


getPosts = () =>  {

    $.ajax({

        type: 'get',

        url: urlname,

        success: (data) => {

            this.setState( { posts: data } )

        }

    });

}

或者你可以像這樣使用bind


getPosts = () =>  {

    $.ajax({

        type: 'get',

        url: urlname,

        success: function(data) {

            this.setState({ posts: data })

        }.bind(this)

    });

}


查看完整回答
反對 回復(fù) 2019-11-20
?
小唯快跑啊

TA貢獻(xiàn)1863條經(jīng)驗 獲得超2個贊

這個問題與失去的環(huán)境相關(guān)的這個。請嘗試以下方法:


let self = this;

getPosts = () =>  {

    $.ajax({

        type: 'get',

        url: urlname,

        success: function(data) {

            self.setState( { posts: data } )

        }

    });

}

或者您可以使用bind:


getPosts = () =>  {

        $.ajax({

            type: 'get',

            url: urlname,

            success: function(data) {

                self.setState( { posts: data } )

            }

        });

    }.bind(this)


查看完整回答
反對 回復(fù) 2019-11-20
?
慕姐8265434

TA貢獻(xiàn)1813條經(jīng)驗 獲得超2個贊

您必須將上下文存儲到變量中,因為“ this”引用在回調(diào)中將不可用。請嘗試以下解決方案:


getPosts = () =>  {

let that=this;

    $.ajax({

        type: 'get',

        url: urlname,

        success: function(data) {

            that.setState( { posts: data } )

        }

    });

}

分享編輯


查看完整回答
反對 回復(fù) 2019-11-20
  • 3 回答
  • 0 關(guān)注
  • 1118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號