【问题标题】:Cannot read property 'id' of null From Realm database无法从领域数据库中读取 null 的属性“id”
【发布时间】:2021-02-08 17:26:08
【问题描述】:

当我想导出默认领域配置 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)

【问题讨论】:

    标签: javascript mongodb typescript react-native realm


    【解决方案1】:

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

    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);
        },
      },
    });
    

    【讨论】:

      【解决方案2】:

      可能使用(添加问号)

      useRealmApp?.currentUser?.id

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

      虽然,这似乎不是使用 react native 的正确方法,但您可能应该创建一个 store (redux/useContext),然后监视您的用户登录/注销,并更新您的用户/分区状态。

      【讨论】:

      • 我已经添加了它们,但仍然抛出错误。但是,当我评论代码并登录,然后取消评论代码并重新运行应用程序时,应用程序将在用户定义时正常工作。我将它与 redux 一起使用,并想在 redux-thunk 函数中使用 useRealmApp 来进行 api 调用
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多