【发布时间】:2020-05-11 18:38:19
【问题描述】:
我想使用react native 构建一个应用程序并实现realm。本来就是有一些播放列表和歌曲的,歌曲应该可以添加到播放列表中。
播放列表:
export class Playlist {
public id: number;
public name: string;
public color: string;
public songs: Song[];
constructor(id: number, name: string, color: string, songs: Song[]) {
this.id = id;
this.name = name;
this.color = color;
this.songs = songs;
}
static schema: Realm.ObjectSchema = {
name: 'Playlist',
primaryKey: 'id',
properties: {
id: 'int',
name: 'string',
color: 'string',
songs: 'Song[]',
},
};
}
歌曲:
export class Song {
public id: number;
public title: string;
public artist: string;
constructor(id: number, title: string, artist: string) {
this.id = id;
this.title = title;
this.artist = artist;
}
static schema: Realm.ObjectSchema = {
name: 'Song',
primaryKey: 'id',
properties: {
id: 'int',
title: 'string',
artist: 'string',
},
};
}
领域:
const initData = () => {
const songs = [
new Song(0, 'Avicii', 'Heaven'),
// some songs
];
const playlists = [
new Playlist(0, 'Favorite Songs', 'purple', []),
// some playlists
];
songs.forEach(song => {
Song.insertSong(song);
});
playlists.forEach(playlist => {
Playlist.insertPlaylist(playlist);
});
};
const databaseOptions = {
path: 'playlists.realm',
schema: [Playlist.schema, Song.schema],
};
let realmInstance: Realm | null;
const getRealm = (): Realm => {
if (realmInstance == null) {
realmInstance = new Realm(databaseOptions);
initData();
}
return realmInstance!;
};
export default getRealm;
我总是得到错误:
TypeError: undefined is not an object (evaluating '_playlist.Playlist.schema')
我不知道为什么。如果您需要更多代码,请告诉我。
我是 react native 和 JavaScript 和 TypeScript 的新手。我习惯使用 Java 开发 Android 应用,所以也许我犯了一些愚蠢的错误,我不知道。
【问题讨论】:
标签: react-native realm