CRUD — 读取 — React Native SDK
读取操作是用于查找存储在 Realm 中的数据的查询。Realm 中的数据是实时的,这意味着对象始终反映其最近保存的状态,并且读取操作永远不会阻塞。对象会自动更新以响应更改,因此您可以在应用程序中查看最新数据,而无需运行新查询。
使用以下 @realm/react
钩子读取 Realm 中的数据:
useObject()
:按照主键查找特定对象。useQuery()
:按对象类型获取对象集合。
这些钩子会返回活动对象,当 Realm 中的数据发生变化时,这些对象会自动更新。更新这些钩子返回的对象时,调用该钩子的组件会重新显示。
本页中的示例使用以下模式:
class Person extends Realm.Object { static schema = { name: 'Person', properties: { name: 'string', age: 'int?', }, }; }
class Task extends Realm.Object { static schema = { name: 'Task', properties: { _id: 'int', name: 'string', priority: 'int?', progressMinutes: 'int?', assignee: 'Person?', }, primaryKey: '_id', }; }
class Person extends Realm.Object<Person> { name!: string; age?: number; static schema: ObjectSchema = { name: 'Person', properties: { name: 'string', age: 'int?', }, }; }
class Task extends Realm.Object<Task> { _id!: number; name!: string; priority?: number; progressMinutes?: number; assignee?: Person; age?: number; static schema: ObjectSchema = { name: 'Task', properties: { _id: 'int', name: 'string', priority: 'int?', progressMinutes: 'int', assignee: 'Person?', }, primaryKey: '_id', }; }
按主键查找特定对象
如果您知道给定对象的主键,则可以通过向 useObject()
钩子传递类的类型和主键来直接查找。
在以下 TaskItem
组件示例中,我们使用 useObject()
钩子根据主键查找任务:_id
。然后,我们在 UI 中显示任务名称和优先级。
const TaskItem = ({_id}) => { const myTask = useObject(Task, _id); return ( <View> {myTask ? ( <Text> {myTask.name} is a task with the priority of: {myTask.priority} </Text> ) : null} </View> ); };
const TaskItem = ({_id}: {_id: number}) => { const myTask = useObject(Task, _id); return ( <View> {myTask ? ( <Text> {myTask.name} is a task with the priority of: {myTask.priority} </Text> ) : null} </View> ); };
查询对象类型并筛选结果
useQuery()
钩子会以 Realm.Results对象的形式返回与查询匹配的Realm对象集合。 基本查询会匹配域中给定类型的所有对象,但您也可以对集合应用过滤以查找特定对象。
过滤器根据一个或多个对象属性的值选择结果子集。Realm 允许您使用 Realm 查询语言过滤数据,这是一种基于字符串的查询语言,用于在从 Realm 检索对象时限制搜索。
对查询结果集合调用filtered()以筛选查询。 将 RQL 查询作为参数传递给filtered()
。
在以下 TaskList
组件示例中,我们:
通过将 "Task" 传递给
useQuery()
钩子,来获取所有Task
对象。通过向
filtered()
传递查询,获取所有高优先级任务和低进度任务。通过映射函数呈现文本组件列表,显示高优先级和低进度任务的信息。
const TaskList = () => { const [priority, setPriority] = useState(4); // filter for tasks with a high priority const highPriorityTasks = useQuery( Task, (tasks) => { return tasks.filtered("priority >= $0", priority); }, [priority] ); // filter for tasks that have just-started or short-running progress const lowProgressTasks = useQuery(Task, tasks => { return tasks.filtered( '$0 <= progressMinutes && progressMinutes < $1', 1, 10, ); }); return ( <> <Text>Your high priority tasks:</Text> {highPriorityTasks.map(taskItem => { return <Text>{taskItem.name}</Text>; })} <Text>Your tasks without much progress:</Text> {lowProgressTasks.map(taskItem => { return <Text>{taskItem.name}</Text>; })} </> ); };
const TaskList = () => { const [priority, setPriority] = useState(4); // filter for tasks with a high priority const highPriorityTasks = useQuery( Task, tasks => { return tasks.filtered('priority >= $0', priority); }, [priority], ); // filter for tasks that have just-started or short-running progress const lowProgressTasks = useQuery(Task, tasks => { return tasks.filtered( '$0 <= progressMinutes && progressMinutes < $1', 1, 10, ); }); return ( <> <Text>Your high priority tasks:</Text> {highPriorityTasks.map(taskItem => { return <Text>{taskItem.name}</Text>; })} <Text>Your tasks without much progress:</Text> {lowProgressTasks.map(taskItem => { return <Text>{taskItem.name}</Text>; })} </> ); };
查询对象类型并对结果排序
排序操作允许您配置 Realm 返回查询对象的顺序。您可以根据结果集合中对象的一个或多个属性进行排序。仅当您对结果进行显式排序时,Realm 才能保证结果顺序一致。
要对查询进行排序,请对查询结果集合上调用 sorted() 方法。
在以下 TaskList
组件示例中,我们使用 useQuery()
钩子来初始检索 Task 对象集。然后,我们使用 sorted()
方法以各种方式处理数据:
根据任务名称的字母顺序(升序)对对象进行排序。
根据任务名称的字母顺序(降序)对对象进行排序。
根据任务优先级(按降序)和任务名称(按升序)对对象进行排序。
根据受让人对象名称的字母顺序(升序)对对象进行排序。
最后,我们映射每个任务列表,并将它们呈现在 UI 中。
const TaskList = () => { // retrieve the set of Task objects const tasks = useQuery(Task); // Sort tasks by name in ascending order const tasksByName = useQuery(Task, tasks => { return tasks.sorted('name'); }); // Sort tasks by name in descending order const tasksByNameDescending = useQuery(Task, tasks => { return tasks.sorted('name', true); }); // Sort tasks by priority in descending order and then by name alphabetically const tasksByPriorityDescendingAndName = useQuery(Task, tasks => { return tasks.sorted([ ['priority', true], ['name', false], ]); }); // Sort Tasks by Assignee's name. const tasksByAssigneeName = useQuery(Task, tasks => { return tasks.sorted('assignee.name'); }); return ( <> <Text>All tasks:</Text> {tasks.map(task => ( <Text>{task.name}</Text> ))} <Text>Tasks sorted by name:</Text> {tasksByName.map(task => ( <Text>{task.name}</Text> ))} <Text>Tasks sorted by name descending:</Text> {tasksByNameDescending.map(task => ( <Text>{task.name}</Text> ))} <Text> Tasks sorted by priority descending, and name alphabetically: </Text> {tasksByPriorityDescendingAndName.map(task => ( <Text> {task.name} </Text> ))} <Text>Tasks sorted by assignee name:</Text> {tasksByAssigneeName.map(task => ( <Text>{task.name}</Text> ))} </> ); };
const TaskList = () => { // retrieve the set of Task objects const tasks = useQuery(Task); // Sort tasks by name in ascending order const tasksByName = useQuery(Task, tasks => { return tasks.sorted('name'); }); // Sort tasks by name in descending order const tasksByNameDescending = useQuery(Task, tasks => { return tasks.sorted('name', true); }); // Sort tasks by priority in descending order and then by name alphabetically const tasksByPriorityDescendingAndName = useQuery(Task, tasks => { return tasks.sorted([ ['priority', true], ['name', false], ]); }); // Sort Tasks by Assignee's name. const tasksByAssigneeName = useQuery(Task, tasks => { return tasks.sorted('assignee.name'); }); return ( <> <Text>All tasks:</Text> {tasks.map(task => ( <Text>{task.name}</Text> ))} <Text>Tasks sorted by name:</Text> {tasksByName.map(task => ( <Text>{task.name}</Text> ))} <Text>Tasks sorted by name descending:</Text> {tasksByNameDescending.map(task => ( <Text>{task.name}</Text> ))} <Text> Tasks sorted by priority descending, and name alphabetically: </Text> {tasksByPriorityDescendingAndName.map(task => ( <Text> {task.name} </Text> ))} <Text>Tasks sorted by assignee name:</Text> {tasksByAssigneeName.map(task => ( <Text>{task.name}</Text> ))} </> ); };