【问题标题】:Looping api calls in redux-thunk (React redux application)在 redux-thunk 中循环 api 调用(React redux 应用程序)
【发布时间】:2016-12-11 01:55:14
【问题描述】:

我的应用程序的 redux 存储中有一个类似的 JSON 对象:

tables: [
{
  "id":"TableGroup1",
  "objs":[
    {"tableName":"Table1","fetchURL":"www.mybackend.[....]/get/table1"},
    {"tableName":"Table2","fetchURL":"www.mybackend.[....]/get/table2"},
    {"tableName":"Table3","fetchURL":"www.mybackend.[....]/get/table3"}
  ]
},{
  "id":"TableGroup2",
  "objs":[
    {"tableName":"Table4","fetchURL":"www.mybackend.[....]/get/table4"},
    {"tableName":"Table5","fetchURL":"www.mybackend.[....]/get/table5"},
    {"tableName":"Table6","fetchURL":"www.mybackend.[....]/get/table6"}
  ]
 }
];

要加载它,我使用以下调用(TableApi 是本地加载的模拟 api,beginAjaxCalls 跟踪当前活动的 Ajax 调用数量);

export function loadTables(){
  return function(dispatch,getState){
    dispatch(beginAjaxCall());
    return TableApi.getAllTables().then(tables => {
        dispatch(loadTablesSuccess(tables));
    }).then(()=>{

       //Looping through the store to execute sub requests

    }).catch(error => {
        throw(error);
    });
  };
}

然后我想遍历我的表,调用不同的 URL 并填充一个名为 data 的新字段,以便调用后的对象看起来像这样;

{"tableName":"Table1","fetchURL":"www.mybackend.[....]/get/table1","data":[{key:"...",value:"..."},{key:"...",value:"..."},{key:"...",value:"..."},.....]}

通过调用 fetch url 会频繁更新数据,然后表格应该在视图中重新呈现。

这引出了我的问题: - 这在建筑上合理吗? - redux 将如何处理频繁的更改? (由于不可变性,我是否会通过频繁深度复制具有 10,000 多个数据条目的表实例来解决性能问题)

更重要的是,我可以放置什么代码来替换注释,以使其达到预期目的?我试过了;

let i;
for(i in getState().tables){
  let d;
  for(d in getState().tables[i].objs){
     dispatch(loadDataForTable(d,i));
  }
}

然而,这段代码似乎不是最好的实现,我得到了错误。

欢迎提出建议,谢谢!

【问题讨论】:

    标签: asynchronous reactjs promise redux redux-thunk


    【解决方案1】:

    首先,您不需要制作所有表的深层副本。 为了不变性,您只需要复制更改的项目。 对于您的数据结构,它看起来像这样:

    function updateTables(tables, table) {
      return tables.map(tableGroup => {
        if(tableGroup.objs.find(obj => table.tableName === obj.tableName)) {
           // if the table is here, copy group
           retrun updateTableGroup(tableGroup, table);
        } else {
           // otherwise leave it unchanged
           return tableGroup;
        }
      })
    }
    
    function updateTableGroup(tableGroup, table) {
      return {
        ...tableGroup,
        objs: tableGroup.objs.map(obj => {
          return table.tableName === obj.tableName  ? table : obj;
        }) 
      };
    }
    

    【讨论】:

      猜你喜欢
      • 2019-06-07
      • 2017-08-28
      • 2019-02-07
      • 2019-01-24
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 2019-02-02
      • 2017-02-04
      相关资源
      最近更新 更多