在多个屏幕上打开领域时反应本机错误

react native error when opening realm on more than one screen

我有一个关于在 react-native 中创建和使用领域数据库的问题。

我有两个屏幕,负责执行CRUD等操作,category.js和client.js

category.js中我有以下构造函数

constructor(props) {
    super(props);
    realm = new Realm({
        schema: [{ name: 'category', primaryKey: 'id', properties: { id: 'int', descricao: 'string', status: 'bool' } }]
    })
}

cliente.js 我有

constructor(props) {
    super(props);
    realm = new Realm({
        schema: [{ name: 'client', primaryKey: 'id', properties: { id: 'int', nome: 'string', cpf: 'string', celular: 'string', status: 'bool' } }]
    })
}

现在我有以下疑惑

对于这个模式,我是否有一个包含表类别和客户的数据库?

当我在 client.js 屏幕上并且我想转到 category.js 时,我收到以下错误消息:已在当前线程上以不同的模式打开。

如何关闭或打开连接,以便我可以在两个屏幕上使用领域?

您没有在尝试创建新实例的新屏幕上打开 realm。这就是您遇到问题的原因。您的应用程序中应该只有一个 realm 实例。

  1. 创建一个导入 realm 依赖项的文件。
  2. 在此文件中创建您需要的所有模式。
  3. 创建一个 new Realm() 实例并将您的模式添加到其中
  4. 导出 realm 的新实例。
  5. 不要在您的组件中使用 realm,而是使用您刚刚创建的 realm 实例。

realm.js

import Realm from 'realm';

class Category extends Realm.Object {}
Category.schema = {
  name: 'category',
  primaryKey: 'id',
  properties: {
    id: 'int',
    descricao: 'string',
    status: 'bool'
  }
};

class Client extends Realm.Object {}
Client.schema = {
  name: 'client',
  primaryKey: 'id',
  properties: {
    id: 'int',
    nome: 'string',
    cpf: 'string',
    celular: 'string',
    status: 'bool'
  }
};

const RealmInstance = new Realm({ schema: [Category, Client] });
export default RealmInstance;

那么按照下面的方式导入应该就可以了

import realm from './path/to/realm.js'

您可以通过查看他们的 example 来了解 realm 是如何做到的。