typescript - 替换集合中实体的最简洁方法
问题描述
实体适配器支持使用“updateOne”方法调用更新集合。但是,当更新值的键不存在时,这会导致特定实体不被更新。请参阅代码示例。
但是,在内部,实体适配器使用Object.assign()
which while is nice 并不总是我想要的。我希望它基本上取代有问题的实体。
此外,如果所讨论的对象具有结构 A(见下文)。然后发生了一些任意的数据库操作并将更新的 JSON 返回到前端。reducer 最终会在表单中获得该信息。
const originalValue: MyClass = new MyClass('value 1', 'value 2');
const updatedValueFromServer: MyClass = new MyClass('updated');
Then internally to the entity adapter it looks like
const updateValue = Object.assign(originalValue, updatedValueFromServer);
// which would result in ...
// { key1: 'updated', key2: 'value 2' }
// while I would like
// { key1: 'updated' }
// Or
// { key1: 'updated', key2: null }
case ActionTypes.UPDATE_SUCCESS:
return collectionAdapter.updateOne({
changes: action.payload.alertSubscription,
id: action.payload.alertSubscription.uniqueID
}, {
...state,
isLoading: false,
error: null
});
export class MyClass {
constructor(public key1?: string, public key2?: string) { }
}
我希望它简单地替换集合中的值,而不是试图通过内部调用“Object.assign()”来进行不良更新。或者,以某种方式将对象中的键设置为 null 将是有益的。
解决方案
setOne is the way to go.
setOne(payload, state);
addOne: Add one entity to the collection
addMany: Add multiple entities to the collection
setAll: Replace current collection with provided collection
setOne: Add or Replace one entity in the collection
removeOne: Remove one entity from the collection
removeMany: Remove multiple entities from the collection, by id or by predicate
removeAll: Clear entity collection
updateOne: Update one entity in the collection. Supports partial updates.
updateMany: Update multiple entities in the collection. Supports partial updates.
upsertOne: Add or Update one entity in the collection. Supports partial updates.
upsertMany: Add or Update multiple entities in the collection. Supports partial updates.
map: Update multiple entities in the collection by defining a map function, similar to Array.map
推荐阅读
- sql - Upsert/on 与串行主键冲突
- java - Hibernate 5持久化并刷新以该实例结尾的实体在数据库中尚未作为行存在
- angular - NgForm.patchValue 在 ngOnInIt 中不起作用,但在单击处理程序中调用时工作正常
- networking - ns-3 网状网络模拟中的畸形动作帧
- python - 为什么即使 `print(chr(128))` 工作正常,`file.write(chr(128))` 在 Python 中也会返回错误?
- android - 将数据从 React 本机应用程序发送回本机应用程序
- tensorflow - 与 TensorFlow 并行在多个 minibatch 上训练 GPU
- python - 正则表达式排除特定的特殊字符、空格和字母
- html - Angular 6 - href 被附加到基本 url
- javascript - 确定数据是 json 还是 string 并根据它执行逻辑