如何修复React中的“无法读取未定义的属性'setState'”

我的应用程序从 Firebase 实时数据库检索数据并尝试以“状态”加载它,但收到错误“无法读取setState未定义的属性”。


我试图在构造函数中添加绑定,但它不起作用


import React from 'react';


import { View } from '@vkontakte/vkui';


import * as firebase from "firebase/app";

import {config} from './dbinit' // import firebase config

import "firebase/database";



import Home from './panels/Home';




class App extends React.Component {

    constructor(props) {

        super(props);

        this.setState = this.setState.bind(this);

        this.state = {

            activePanel: 'home',

            db: null,

            loading: true,

        };

        console.log("init");

    }


    componentDidMount = () => {

        let ref = firebase

         .initializeApp(config)

         .database()

         .ref();


        ref.once("value").then(function onSuccess(res) {

            console.log("success", res.val())



            this.setState({db: res.val(), loading: false})

            // ERROR GOES HERE 'Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined'



        });

    }


    go = (e) => {

        this.setState({activePanel: e.currentTarget.dataset.to})

    };



    render() {

        const { loading, db } = this.state;

        return loading ? (

            <div>loading...</div>

        ) : (

            <View activePanel={this.state.activePanel}>

                <div>loaded</div>

            </View>


        );

    }

}


export default App;


我期望正确的工作setState但实际有错误Cannot read property 'setState' of undefined'


至尊宝的传说
浏览 528回答 3
3回答

红糖糍粑

你从不久就失去了上下文。使用的函数:&nbsp; &nbsp; ref.once("value").then(function onSuccess(res) {&nbsp; &nbsp; &nbsp; &nbsp; console.log("success", res.val())&nbsp; &nbsp; &nbsp; &nbsp; this.setState({db: res.val(), loading: false})&nbsp; &nbsp; &nbsp; &nbsp; // ERROR GOES HERE 'Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined'&nbsp; &nbsp; });使用箭头函数像这样:ref.once("value").then((res) => {&nbsp; &nbsp; console.log("success", res.val())&nbsp; &nbsp; this.setState({db: res.val(), loading: false})&nbsp; &nbsp; // ERROR GOES HERE 'Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined'});

海绵宝宝撒

原因是因为您使用的是基于被调用者而不是基于词法范围动态绑定 this 关键字的常规函数......因为这段代码在严格模式下运行(因为它在一个类中)所以 this 关键字被解析作为未定义。如果您希望保留上下文,您必须绑定函数或使用箭头函数(根据词法范围绑定 this 关键字)转换这个ref.once("value").then(function onSuccess(res) {&nbsp; &nbsp; &nbsp; &nbsp; console.log("success", res.val())&nbsp; &nbsp; &nbsp; &nbsp; this.setState({db: res.val(), loading: false})&nbsp; &nbsp; &nbsp; &nbsp; // ERROR GOES HERE 'Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined'});对此ref.once("value").then(res => this.setState({db: res.val(), loading: false}));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript