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

类组件中的状态变量在我尝试检索它时未定义

类组件中的状态变量在我尝试检索它时未定义

慕码人2483693 2023-03-18 16:49:00
我有这个类组件:    import React, { Component } from 'react';import '../styles/App.css';import { openDB } from 'idb';class MensaInfo extends Component {    constructor() {        super();        this.state = {            id: 0,        };    }    getMensaId = async () => {        var db = await openDB('PWA_DATA', 2);        var transaction = db.transaction(["user"], "readonly");        var store = transaction.objectStore('user');        var mensa = await store.get('lieblingsmensa');        this.id = mensa['lieblingsmensa'];        console.log(this.id)        db.close()    }    fetchMensa = async () => {        const data = await fetch(`https://openmensa.org/api/v2/canteens/${this.id}/`);        const info = await data.json();    }    update = () => {        this.getMensaId()        this.fetchMensa()    }    componentDidMount = () => {        window.addEventListener('load', this.update());    }    render() {        return (            <div className="dive">                {this.id}            </div>        )    }}export default MensaInfo;我在我的 idb 中有一个 id,我尝试将它用于 api 调用,我可以从 idb 获取 id 并将其保存为状态变量,当我尝试在我的 api 调用函数中使用它时,它显示为未定义,甚至没有显示我设置的 0。getmensaid 中的控制台日志向我显示了正确的值,但我不能将它用于 api 在不同的组件中,它以这种方式工作,但在这方面它不起作用。我究竟做错了什么?
查看完整描述

1 回答

?
侃侃无极

TA贡献2051条经验 获得超10个赞

如我所见,您从不调用 this.setState。


getMensaId = async () => {

    var db = await openDB('PWA_DATA', 2);

    var transaction = db.transaction(["user"], "readonly");

    var store = transaction.objectStore('user');

    var mensa = await store.get('lieblingsmensa');

    // I think the problem is here

    this.setState({id: mensa['lieblingsmensa']});

    //this.id = mensa['lieblingsmensa'];

    console.log(this.id)

    db.close()

}


查看完整回答
反对 回复 2023-03-18
  • 1 回答
  • 0 关注
  • 64 浏览
慕课专栏
更多

添加回答

举报

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