首页 > 解决方案 > 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;
  }
}

每次我想更改单个条目时,我都会犹豫是否复制整个列表。您的解决方案是什么,这里的最佳实践是什么?我很感谢任何建议。

标签: reduxdartflutter

解决方案


推荐阅读