React Native调用useRealm()报Realm上下文未找到错误求助
React Native中Realm useRealm()报错排查与解决
问题场景
在React Native应用中配置Realm时,使用RealmProvider包裹导航容器,但在ProfileScreen中调用useRealm()时出现以下错误:
Realm context not found. Did you call useRealm() within a <RealmProvider/?
相关代码
App组件代码
const Stack = createNativeStackNavigator(); const defaultPathLocalRealm = createRealmContext({ schema: [Profile] }); const {RealmProvider} = defaultPathLocalRealm; function App(): JSX.Element { return ( <AppProvider id={'testmongo-lvvnx'}> <UserProvider fallback={Login}> <RealmProvider sync={{flexible: true, onError: console.error}}> <NavigationContainer> <Stack.Navigator> <Stack.Screen name='SplashScreen' component={SplashScreen}/> <Stack.Screen name='Login' component={Login}/> <Stack.Screen name='ProfileScreen' component={ProfileScreen}/> </Stack.Navigator> </NavigationContainer> </RealmProvider> </UserProvider> </AppProvider> ); } export default App;
ProfileScreen代码
const ProfileScreen = () => { const realm = useRealm() const app = useApp() const save = async () => { try { realm.write(() => { const res = realm.create('Profile', {_id: 'klsdfds7fsdfhgfhfg8ysdfh', name: 'Besart', email: "besart.haxhidema@gmail.com"}) console.log(res) }) } catch (error) { console.log(error) } } const logout = () => { app.currentUser?.logOut() } return( <View> <Button onPress={save} title="Save"/> <Button onPress={logout} title="Logout"/> </View> ) } export default ProfileScreen
Profile Schema代码
import Realm from 'realm'; export class Profile extends Realm.Object<Profile>{ _id!: string; name!: string; email?: string; static schema = { name: 'Profile', properties: { _id: 'string', name: 'string', email: 'string' }, primaryKey: '_id' } }
解决方法
1. 确保useRealm来自同一个自定义Realm Context
这是最常见的问题:你创建了自定义的Realm Context defaultPathLocalRealm,但如果ProfileScreen直接从realm包导入useRealm,就会找不到对应的Context。
步骤1:在App组件文件中导出自定义的useRealm
修改App组件中的解构语句,同时导出useRealm:const { RealmProvider, useRealm } = defaultPathLocalRealm; export { useRealm }; // 新增导出步骤2:在ProfileScreen中导入自定义的useRealm
替换原有导入,使用从App组件文件导出的useRealm:// 替换 import { useRealm } from 'realm'; import { useRealm } from './App'; // 路径根据你的实际文件结构调整
2. 确认组件渲染层级正确性
检查ProfileScreen是否始终在RealmProvider的包裹范围内:你的导航容器已经被RealmProvider包裹,只要ProfileScreen是通过这个导航栈渲染的,层级就没问题。避免在RealmProvider之外通过其他方式(比如全局模态框)渲染ProfileScreen。
3. 补充同步Realm的用户校验
由于你使用了Flexible Sync,操作Realm需要已登录的用户。可以在save函数中增加用户存在性校验,避免未登录时触发错误:
const save = async () => { try { if (!app.currentUser) { console.log('用户未登录,无法操作Realm'); return; } realm.write(() => { const res = realm.create('Profile', {_id: 'klsdfds7fsdfhgfhfg8ysdfh', name: 'Besart', email: "besart.haxhidema@gmail.com"}) console.log(res) }) } catch (error) { console.log(error) } }
内容的提问来源于stack exchange,提问作者Besart
相关产品推荐
相关产品推荐

