Docs 菜单
Docs 主页
/ /
数据类型

UUID - React Native SDK

realm@10.5.0 版本中的新增功能。

UUID (通用唯一标识符)是一个 字节的16 唯一值 UUIDRealm.BSON.UUID。 作为BSON () 的一部分与Realm包捆绑在一起。

您可以使用 UUID 作为对象的唯一标识符。UUID 可索引,您可以将其用作主键

class Profile extends Realm.Object {
static schema = {
name: 'Profile',
primaryKey: '_id',
properties: {
_id: 'uuid',
name: 'string',
},
};
}
class Profile extends Realm.Object<Profile> {
_id!: Realm.BSON.UUID;
name!: string;
static schema: ObjectSchema = {
name: 'Profile',
primaryKey: '_id',
properties: {
_id: 'uuid',
name: 'string',
},
};
}

要将属性定义为 UUID,请在对象模型中将其类型设置为 "uuid"。在写事务中创建 Realm 对象。要将对象的任何唯一标识符属性设置为随机值,请调用 new UUID()。或者向 new UUID() 传递一个字符串,将该唯一标识符属性设置为特定值。

在以下CreateProfileInput示例中,我们为_id字段创建一个具有uuid类型的Profile Realm.Object

CreateProfileInput 组件将执行以下操作:

  • 调用 useRealm() 钩子,访问打开的 Realm 实例。

  • 创建名为 "name" 的名称状态变量
    ,表示配置文件的名称。
  • 创建执行写入事务的 createProfile 方法在
    在该写事务中,我们创建了一个 Profile 对象,其 name 值为“name”状态变量,_id 值为新的 UUID 对象。
  • 呈现 TextInput 组件,允许用户输入工具名称,上述工具为
    配置文件。当用户按下“创建配置文件”按钮时,系统会调用 createProfile 方法并创建 Profile 对象。
1const CreateProfileInput = () => {
2 const realm = useRealm();
3 const [name, setName] = useState('');
4
5 // createProfile creates a new 'Profile' Realm Object with a new UUID based on user input
6 const createProfile = () => {
7 realm.write(() => {
8 realm.create('Profile', {
9 name,
10 _id: new Realm.BSON.UUID(),
11 });
12 });
13 };
14 return (
15 <View>
16 <TextInput
17 placeholder='Name'
18 onChangeText={setName}
19 />
20 <Button
21 title='Create Profile'
22 onPress={createProfile}
23 />
24 </View>
25 );
1const CreateProfileInput = () => {
2 const realm = useRealm();
3 const [name, setName] = useState('');
4
5 // createProfile creates a new 'Profile' Realm Object with a new UUID based on user input
6 const createProfile = () => {
7 realm.write(() => {
8 realm.create('Profile', {
9 name,
10 _id: new Realm.BSON.UUID(),
11 });
12 });
13 };
14 return (
15 <View>
16 <TextInput
17 placeholder='Name'
18 onChangeText={setName}
19 />
20 <Button
21 title='Create Profile'
22 onPress={createProfile}
23 />
24 </View>
25 );

后退

混合

在此页面上