我有这个类组件: 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()
}
添加回答
举报
0/150
提交
取消