慕碼人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 調(diào)用,我可以從 idb 獲取 id 并將其保存為狀態(tài)變量,當(dāng)我嘗試在我的 api 調(diào)用函數(shù)中使用它時,它顯示為未定義,甚至沒有顯示我設(shè)置的 0。getmensaid 中的控制臺日志向我顯示了正確的值,但我不能將它用于 api 在不同的組件中,它以這種方式工作,但在這方面它不起作用。我究竟做錯了什么?
1 回答

侃侃無極
TA貢獻(xiàn)2051條經(jīng)驗(yàn) 獲得超10個贊
如我所見,您從不調(diào)用 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
提交
取消