javascript - 无法读取 null 的属性 'id' 来自 Realm 数据库
当我想导出默认的 Realm 配置 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)
答案#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 是未定义/空,因此你无法读取 .id。
不过,这似乎不是使用 React Native 的正确方式,你可能应该创建一个 store(redux/useContext),然后监控用户的登录/登出,并更新你的用户/分区状态。
