使用 useRealm() 挂钩时出现以下错误:
ERROR 错误:未找到领域上下文。您是否在
中调用了 useRealm()<RealmProvider/>?
为什么我会收到此错误以及如何纠正它?
我已按照 Realm 的 React Native 快速入门进行操作,如下所述:https://www.mongodb.com/docs/realm/sdk/react-native/quick-start/
这是源代码。
App.jsx:
import { createRealmContext } from '@realm/react';
import Realm from 'realm';
import TestView from './src/modules/sandbox/TestView';
class Profile extends Realm.Object {
static schema = {
name: 'Profile',
properties: {
municipality: 'string',
profileName: 'string',
password: 'string',
sessionID: 'string',
},
};
}
const realmConfig = {
schema: [Profile],
};
const { RealmProvider, useObject, useQuery } = createRealmContext(realmConfig);
console.log(realmConfig);
function App() {
return (
<RealmProvider>
<TestView />
</RealmProvider>
);
}
export default App;
TestView.jsx:
import { StyleSheet, Text, View } from 'react-native';
import React from 'react';
import { useRealm } from '@realm/react';
export default function TestView() {
const realm = useRealm();
return (
<View style={styles.container}>
<Text>Hello</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
});
Realm 和 RN 版本:
"realm": "^11.10.1", "@realm/react": "^0.5.1", "react-native": "0.71.11",