Undefined не является объектом, использующим родную область реагирования - PullRequest
0 голосов
/ 25 января 2020

Я хочу создать приложение, используя 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. Я привык к разработке Android приложений с использованием Java, поэтому, возможно, я сделал несколько глупых ошибок, я не знаю.

1 Ответ

0 голосов
/ 26 января 2020

Вы не используете свой реальный экземпляр в initData, вам нужно использовать realm.write, как в следующем примере. Я думаю, что мой маленький кусочек кода должен работать, обновите меня, что у вас есть (лучше использовать Realm asyn c, чем syn c, как вы хотите)

const PersonSchema = {
  name: 'Person',
  properties: {
    // The following property definitions are equivalent
    cars: {type: 'list', objectType: 'Car'},
    vans: 'Car[]'
  }
}

let carList = person.cars;

// Add new cars to the list
realm.write(() => {
  carList.push({make: 'Honda', model: 'Accord', miles: 100});
  carList.push({make: 'Toyota', model: 'Prius', miles: 200});
});

let secondCar = carList[1].model;  // access using an array index

В вашем случае

Realm.open({schema: [Song, PlayList]})
  .then(realm => {
    // ...use the realm instance here
   try {
      realm.write(() => {
         const songs = [
            realm.create('Song',{title: 'Avicii', artist: 'Heaven'}),
         ];

         const playlists = [
           realm.create('Playlist',{name: 'Favorite Songs', color: 'purple', songs: []}),
           // some playlists
         ];
         playlists.forEach(playlist => {
           for (const song of songs){
               playlist.songs.push(song);
            }
         });
      });
   } catch (e) {
     console.log("Error on creation");
   }
  })
  .catch(error => {
    // Handle the error here if something went wrong
  });
...