无法从 Realm 数据库读取 属性 'id' 的 null

Cannot read property 'id' of null From Realm database

当我想要导出默认领域配置时出现错误 useRealm 以便我可以将其用于其他文件

import Realm from "realm";
import { getRealmApp } from "../functions/realmConfig";
import { ItemSchema } from "./itemSchema";

export const app = getRealmApp();
export const useRealmApp = getRealmApp();

export const user = useRealmApp.currentUser;
export const partitionValue = useRealmApp.currentUser.id;

export const config = {
  schema: [ItemSchema], //other schema will be added in the future
  sync: {
    user: user,
    partitionValue: partitionValue, //app.currentUser.id,
  },
};

export const useRealm = new Realm(config);

预期结果是,如果用户未登录,则应显示登录屏幕。但是它抛出这个错误并且没有给我登录的机会:

index.ts?77fd:9 Uncaught TypeError: Cannot read property 'id' of null
    at eval (index.ts?77fd:9)
    at Object../src/realm/index.ts (renderer.js:5394)
    at __webpack_require__ (renderer.js:791)
    at fn (renderer.js:102)
    at eval (testIndex.tsx?956d:10)
    at Object../testIndex.tsx (renderer.js:5438)
    at __webpack_require__ (renderer.js:791)
    at fn (renderer.js:102)
    at eval (App.tsx?d35d:4)

大概会用(加问号)

useRealmApp?.currentUser?.id

因为如果你没有登录,useRealmApp.currentUser就是undefined/null,所以你无法读取.id

不过,这似乎不是使用 React Native 的正确方法,您可能应该创建一个商店 (redux/useContext),然后监控您的用户 login/logout,并更新您的user/partition 个州。

试试这个,但不确定它是否有效

const user: any = Realm.User;

export const useRealm = Realm.open({
  schema: [ItemSchema],
  sync: {
    user: user.prototype,
    partitionValue: app.currentUser?.id!,
    error: (e) => {
      console.log(e);
    },
  },
});