1 个不稳定版本
| 0.1.0 | 2024年3月18日 |
|---|
#5 在 #props
在 syewreal 中使用
12KB
224 行
用法
创建连接
要连接到数据库,使用 use_surreal_login 钩子。该钩子返回一个令牌,必须在 <SurrealContext/> 上下文提供者中使用。
#[function_component]
fn MyComponent(props: &P) -> Html{
let login = Database {
username: "user",
password: "user",
database: "test",
namespace: "test"
};
let token = use_surreal_login("localhost:8000".to_owned(), login);
html! {
<SurrealContext token={token}>
// Your App goes here
</SurrealContext>
}
}
<SurrealContext/> 将挂起您的应用程序,直到登录成功。
查询组件
<Query/> 组件将检索所有匹配给定查询的数据库条目并依次显示它们
html! {
<SurrealContext token={token}>
<Query<Inner> selector="select * from myTable"/>
</SurrealContext>
}
<Query<T>/> 有四个属性
selector: 可以转换为SelectStatement的东西,这包括String和 surreal 记录(surreal 源代码中的Thing)parameters(可选):一个包含(String, String)元组的 Vec,这些元组将被绑定到查询filter(可选):一个 yew 回调Fn(T::Properties) -> bool,用于本地过滤。fallback(可选):一个Html元素,在数据正在检索时将被渲染(在底层使用 yew 暂停)。
<Query/> 将查询结果存储在内部管理的状态中。如果您想操作状态或在多个地方使用相同的查询结果,您将不得不结合使用 <QueryWithState/> 与 use_query_state 钩子
let list_state = use_query_state::<ToDoItemProps>("SELECT * FROM item");
html!{
<QueryWithState<ToDoItem> state={list_state}/>
}
由于状态是外部管理的,因此 <QueryWithState/> 组件没有 selector 和 parameters 字段。
属性
为了使组件 <Inner/> 能够被 <Query/> 渲染,Inner::Properties 需要继承 SurrealProps(除了 Properties,还包括 PartialEq 和 Clone)
#[derive(SurrealProps, Properties, PartialEq, Clone)]
struct InnerProps {
#[id] id: Option<ID>,
name: AttrValue,
}
#[function_component]
fn Inner(props: &InnerProps) -> Html{
// You know what to do here
}
组件的 id 属性可以是一个 ID 或一个 Option<ID>,如果您想从组件创建新的数据库条目,应该选择 Option<ID> 以将 id 设置为 None 在新条目上。
本地属性
为了添加可以本地设置而不是从服务器检索的属性,将它们标记为 #[local]
#[derive(SurrealProps, Properties, PartialEq, Clone)]
struct InnerProps {
id: AttrValue,
name: AttrValue,
#[local]
color: AttrValue
}
它们需要在包装组件上设置,并应用于所有 Inner 组件
<SurrealList<Inner> selector="select * from myTable" color="red"/>
外键
处理外键有两种方式
A) 使用类型为 ForeignKey 的属性(这只是一个 ID 的别名,但更易读)
B) 使用类型为 StaticChild<T> 的属性,其中 T 是可反序列化的结构。这允许通过 FETCH 关键字一次性检索数据,但在更新/创建时,只会将检索到的数据的 id 写入 surreal
"原始" 数据库访问
您可以直接使用 <Query/> 渲染组件,而是可以使用 use_surreal() 钩子来
select:使用Selector从 surreal 检索任意数据update:更新组件的底层数据(本地和远程)。这始终使用MERGE模式,因为无法保证本地结构包含远程表的全部字段。create:创建一个新的数据库条目并使用便利方法将新条目本地存储query:执行任意 SQL 查询并将结果存储
use_surreal().create(
"item".to_owned(),
ToDoItemPropsRemote {
done: false,
// Note how having the type of id be Option<ID>
// enables you to delegate id creation to the Database
id: None,
text: None,
title: "Test".into(),
img: None
},
).execute();
自引用
方法 use_surreal().update() 接收一个 SurrealSelfRef 作为参数,这可以通过使用钩子 use_self_ref() 在组件内部获取。
当执行更新时,如果新数据仍然匹配原始选择器,将从数据库返回的数据用于替换组件的属性,否则数据将从本地存储中删除。
注意:强烈建议在创建自更新组件时使用 use_update_callback 钩子。
依赖项
~37–52MB
~868K SLoC