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

我有这个类组件:


    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 在不同的组件中,它以这种方式工作,但在这方面它不起作用。我究竟做错了什么?


慕码人2483693
浏览 66回答 1
1回答

侃侃无极

如我所见,您从不调用 this.setState。getMensaId = async () => {&nbsp; &nbsp; var db = await openDB('PWA_DATA', 2);&nbsp; &nbsp; var transaction = db.transaction(["user"], "readonly");&nbsp; &nbsp; var store = transaction.objectStore('user');&nbsp; &nbsp; var mensa = await store.get('lieblingsmensa');&nbsp; &nbsp; // I think the problem is here&nbsp; &nbsp; this.setState({id: mensa['lieblingsmensa']});&nbsp; &nbsp; //this.id = mensa['lieblingsmensa'];&nbsp; &nbsp; console.log(this.id)&nbsp; &nbsp; db.close()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript