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

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

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

至尊宝的传说 2021-07-13 17:53:35
我的应用程序从 Firebase 实时数据库检索数据并尝试以“状态”加载它,但收到错误“无法读取setState未定义的属性”。我试图在构造函数中添加绑定,但它不起作用import React from 'react';import { View } from '@vkontakte/vkui';import * as firebase from "firebase/app";import {config} from './dbinit' // import firebase configimport "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'
查看完整描述

3 回答

?
红糖糍粑

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

你从不久就失去了上下文。使用的函数:


    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'



    });

使用箭头函数像这样:


ref.once("value").then((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'



});


查看完整回答
反对 回复 2021-07-15
?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

原因是因为您使用的是基于被调用者而不是基于词法范围动态绑定 this 关键字的常规函数......因为这段代码在严格模式下运行(因为它在一个类中)所以 this 关键字被解析作为未定义。


如果您希望保留上下文,您必须绑定函数或使用箭头函数(根据词法范围绑定 this 关键字)


转换这个


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'



});

对此


ref.once("value").then(res => this.setState({db: res.val(), loading: false}));


查看完整回答
反对 回复 2021-07-15
  • 3 回答
  • 0 关注
  • 527 浏览
慕课专栏
更多

添加回答

举报

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