高级存储操作
Dojo 存储使用操作来更改应用程序底层状态。操作的设计旨在简化与存储的常见交互,因此,例如,操作将自动创建支持 add
或 replace
操作所需的底层结构。
在未初始化的存储中执行深度 add
import Store from '@dojo/framework/stores/Store';
import { add } from '@dojo/framework/stores/state/operations';
const store = new Store<State>();
const { at, path, apply } = store;
const user = { id: '0', name: 'Paul' };
apply([add(at(path('users', 'list'), 10), user)]);
这将产生以下结果
{
"users": {
"list": [
{
"id": "0",
"name": "Paul"
}
]
}
}
即使状态尚未初始化,Dojo 也能够根据提供的路径创建底层层次结构。此操作是安全的,因为 TypeScript 和 Dojo 存储提供了类型安全。这允许用户自然地使用存储使用的 State
接口,而不必担心存储明确持有的数据。
当需要显式状态时,可以使用 test
操作或获取底层数据并以编程方式验证它来断言该信息。
此示例通过使用 test
操作来确保初始化,从而确保 user
始终作为最后一个元素添加到列表的末尾
import Store from '@dojo/framework/stores/Store';
import { test } from '@dojo/framework/stores/state/operations';
const store = new Store<State>();
const { at, path, apply } = store;
apply([test(at(path('users', 'list', 'length'), 0))]);
此示例通过编程自省确保 user
始终作为最后一个元素添加到列表的末尾
import Store from '@dojo/framework/stores/Store';
import { add, test } from '@dojo/framework/stores/state/operations';
const store = new Store<State>();
const { get, at, path, apply } = store;
const user = { id: '0', name: 'Paul' };
const pos = get(path('users', 'list', 'length')) || 0;
apply([
add(at(path('users', 'list'), pos), user),
test(at(path('users', 'list'), pos), user),
test(path('users', 'list', 'length'), pos + 1)
]);
不允许访问状态根,例如尝试执行 get(path('/'))
时将抛出错误。此限制也适用于操作;无法创建更新状态根的操作。@dojo/framework/stores
的最佳实践鼓励访问存储中最小的必要部分。