React Native中Realm的useRealm钩子报错:未找到Realm上下文
解决Realm Context Not Found错误
错误的核心原因是**useRealm()的调用位置错误**:你在App组件中直接调用了useRealm(),但App组件是<RealmProvider>的父组件,<RealmProvider>是在App的return语句中才渲染的,所以App本身并没有处于Realm的上下文环境中,自然无法获取Realm实例。
修复方案
- 删除
App组件中的const realm = useRealm();这行代码,App的职责是提供RealmProvider,不需要直接访问Realm。 - 所有需要访问Realm的逻辑(比如读写操作),必须放在被
<RealmProvider>包裹的子组件中(比如你的RestOfApp组件)。
修改后的完整代码
import React from 'react'; import Realm from 'realm'; import {createRealmContext} from '@realm/react'; import CButton from './src/components/atoms/CButton'; class Profile extends Realm.Object<Profile> { _id!: Realm.BSON.ObjectId; name!: string; static schema = { name: 'Profile', properties: { _id: 'objectId', name: 'string', }, primaryKey: '_id', }; } const realmConfig: Realm.Configuration = { schema: [Profile], }; const {RealmProvider, useRealm, useObject, useQuery} = createRealmContext(realmConfig); const RestOfApp = () => { const realm = useRealm(); const changeProfileName = (profileToChange: Profile, newName: string) => { realm.write(() => { profileToChange.name = newName; }); }; return <CButton onClick={() => {}}>Test</CButton>; }; function App(): JSX.Element { // 移除了错误的useRealm调用 return ( <RealmProvider fallback={() => null}> <RestOfApp /> </RealmProvider> ); }
内容的提问来源于stack exchange,提问作者Nagaraj
相关产品推荐
相关产品推荐

