如何解决Dexiejs db.versionstores不会在我的React应用程序中初始化表,但在Codesandbox和StackBlitz中可以正常工作
我正在尝试使用Dexie初始化indexedDB,它似乎在StackBlitz和Codesandbox中不起作用,但是当我将代码移植到我的应用程序时{{3} })。 (与数据库相关的代码位于考试历史记录分支中。)
在初始渲染时,触发TypeError: Cannot read property 'mapToClass' of undefined
在StackBlitz中的调试器上检查db时,它将考试,答案和问题显示为Table $$ 1。但是,在本地它不确定。
db.ts
import Dexie from "dexie";
import { Answer,Question,Exam } from "./model";
class ExamDatabase extends Dexie {
public exams: Dexie.Table<Exam,number>;
public questions: Dexie.Table<Question,number>;
public answers: Dexie.Table<Answer,number>;
constructor() {
super("ExamDatabase");
const db = this;
db.version(1).stores({
exams:
"&gid,examNumber,examType,correct,currentQuestion,time,isPaused",questions: "&gid,examId,question,explanation,isMultipleChoice",answers: "&gid,questionId,type,choice,isSelected,isCorrect"
});
debugger
db.exams.mapToClass(Exam);
db.questions.mapToClass(Question);
db.answers.mapToClass(Answer);
}
}
export const db = new ExamDatabase();
model.ts
import cuid from "cuid";
export abstract class AbstractEntity {
constructor(public gid?: string) {
gid ? (this.gid = gid) : (this.gid = cuid());
}
equals(e1: AbstractEntity,e2: AbstractEntity) {
return e1.gid === e2.gid;
}
}
export class Answer extends AbstractEntity {
constructor(
public questionId: string,public choice: string,public isSelected: boolean,public isCorrect: boolean,gid?: string
) {
super(gid);
}
}
export class Question extends AbstractEntity {
answers: Answer[];
constructor(
public examId: string,public question: string,public explanation: string,public isMultipleChoice: boolean,gid?: string
) {
super(gid);
Object.defineProperties(this,{
answers: { value: [],enumerable: false,writable: true },});
}
}
export class Exam extends AbstractEntity {
questions: Question[];
constructor(
public examNumber: string,public examType: string,public correct: number,public currentQuestion: number,public time: string,public isPaused: boolean,{
questions: { value: [],});
}
}
记录“ db” repo
解决方法
看来解决方法是用db构造函数中的表方法替换mapToClass。
db.exams = db.table("exams");
db.questions = db.table("questions");
db.answers = db.table("answers");
但是,如果有人能解释为什么mapToClass可以在codeandbox env中而不是在本地服务器中工作,我仍然很感激。
Dexie版本3.0.2
打字稿版本3.9.7
和tsconfig文件:
{
"compilerOptions": {
"target": "es5","lib": [
"dom","dom.iterable","esnext"
],"allowJs": true,"skipLibCheck": true,"esModuleInterop": true,"allowSyntheticDefaultImports": true,"strict": true,"strictPropertyInitialization": false,"forceConsistentCasingInFileNames": true,"module": "esnext","moduleResolution": "node","resolveJsonModule": true,"isolatedModules": true,"noEmit": true,"jsx": "react"
},"include": [
"src"
]
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。