首頁 > web前端 > js教程 > 主體

如何解決 React 綁定回呼函數時出現「this.setState is not a function」錯誤?

Mary-Kate Olsen
發布: 2024-10-24 05:03:30
原創
890 人瀏覽過

How to Resolve

React 中的錯誤:「this.setState 不是函數」

當嘗試在未綁定的回呼函數中存取this.setState 時,通常會發生此錯誤正確的上下文。在 React 中,this 指的是元件實例,必須維護正確的上下文來存取其方法(如 setState)。

在給定的程式碼片段中,問題出現在VK API 呼叫的回呼函數中:

VK.api('users.get',{fields: 'photo_50'},function(data){
    if(data.response){
        this.setState({ //the error happens here
            FirstName: data.response[0].first_name
        });
        console.info(this.state.FirstName);
    }
});
登入後複製

回呼函數是在不同的作用域中定義的,而this 不引用組件實例。要解決此問題,需要將回呼函數綁定到正確的上下文:

VK.api('users.get',{fields: 'photo_50'},function(data){
    if(data.response){
        this.setState({ //the error happens here
            FirstName: data.response[0].first_name
        });
        console.info(this.state.FirstName);
    }
}.bind(this));
登入後複製

透過將回呼函數綁定到this,我們確保this 引用回調中的元件實例,從而允許我們存取this. setState。

在某些情況下,可能需要綁定啟動和 API 呼叫:

VK.init(function(){
    console.info("API initialisation successful");
    VK.api('users.get',{fields: 'photo_50'},function(data){
        if(data.response){
            this.setState({ //the error happens here
                FirstName: data.response[0].first_name
            });
            console.info(this.state.FirstName);
        }

    }.bind(this));
}.bind(this), function(){
    console.info("API initialisation failed");

}, '5.34');
登入後複製

這確保 this 在整個過程中引用元件實例,包括啟動和 API 呼叫。

以上是如何解決 React 綁定回呼函數時出現「this.setState is not a function」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!