redux - Flutter 中使用嵌套 AppState 的 reducer 的最佳实践是什么
问题描述
如果 AppState 包含列表或其他复杂对象,我想知道 AppState 减速器的最佳实践。
举个例子:
设置:假设我正在编写一个体重跟踪应用程序,并且对于每个体重条目,都附有日期和评论。我想显示有关用户体重条目的各种信息,所以我决定将它们提升到 appstate 中。我决定将它们与用户数据分开并将它们保存在一个单独的列表中,以使 appstate 尽可能平坦,并将不同的方面(用户数据、设置、权重条目)分开。
代码:
应用状态:
class AppState{
//username, birthdate, etc.
List<Entry> entries;
}
入口:
class Entry{
String userId;
double weight;
DateTime date;
String comment;
}
2 修改/添加条目的操作:
class UpdateCommentOnEntry{
int index;
String comment;
}
class AddEntry{
Entry entry;
}
任务:在 AppState Reducer 中处理此列表的最佳方法是什么?2 行动?
关注点:移动设备上的性能和内存管理。基本上我想尽可能少地复制。
可能的解决方案:
-1)据我所知,这个解决方案是错误的/违反了 Redux 标准,因为它改变了当前状态:
AppState reducer(AppState state, dynamic action) {
if(action is UpdateCommentOnEntry){
state.entries[action.index].comment=action.comment;
} else if(action is AddEntry){
state.entries.add(action.entry);
}
return state;
}
1)此解决方案复制整个列表
AppState reducer(AppState state, dynamic action) {
if(action is UpdateCommentOnEntry){
List<Entry> newList;
for(int i = 0; i<state.entries.length; i++){
if(i!=action.index){
newList.add(state.entries[i]);
} else{
newList.add(state.entries[i].copyWith(comment: action.comment));
}
}
return state.copyWith(entries = newList);
} else if(action is AddEntry){
List<Entry> newList = List<Entry>.from(state.entries);
newList.entries.add(action.entry);
return state.copyWith(entries: newList);
} else {
return state;
}
}
2)这个解决方案不复制列表,但复制了AppState,但它仍然在同一个列表中引用。而且这个 List 确实发生了变异,那么这是否也违反了 Redux 标准?
AppState reducer(AppState state, dynamic action) {
if(action is UpdateCommentOnEntry){
state.entries[i] = state.entries[i].copyWith(comment: action.comment);
return state.copyWith(entries: state.entries);
} else if(action is AddEntry){
List<Entry> newList = List<Entry>.from(state.entries);
newList.entries.add(action.entry);
return state.copyWith(entries: newList);
} else {
return state;
}
}
每次我想更改单个条目时,我都会犹豫是否复制整个列表。您的解决方案是什么,这里的最佳实践是什么?我很感谢任何建议。
解决方案
推荐阅读
- sql-server - 在计算字段中使用聚合函数
- python - 如何最小化 x 轴上的日期时间刻度数
- mysql - 在同一张表中使用外键
- ios - 每个请求都有不同的 json 对象
- python - 更改固定关键字的 django haystack 搜索结果准确性
- excel - 公开 Excel InlineShapes 以进行编辑
- python - 获取终端输出颜色/返回文本颜色
- arrays - Labview 阵列索引跟踪
- amazon-redshift - Google Data Studio 中日期维度的 COUNT DISTINCT 聚合不准确
- javascript - 仅在表格数据动画期间隐藏垂直滚动条