减速器不断返回空数组

时间:2019-04-20 06:44:32

标签: javascript reactjs typescript

我试图在用数据填充完reducer后返回一个数组,但是它总是返回一个空数组。

export default function dashboards(state: any = dashboardsState, action: any) {
 // more code
  if (action.type === Types.LOAD_DASHBOARD_SUCCESS) {
    // create the cards holder in the store
    var cardsSkull: any = [];
    Object.keys(action.payload.lists).map((idLis: any) => {
      cardsSkull[idLis] = {};
      console.log("still up");
    });
    action.payload.importedDashboards.map((impDash: any) => {
      Object.keys(impDash.mappedLists).map((key: any) => {
        const mpList = impDash.mappedLists[key];
        cardsSkull[mpList.idlistLocal][impDash.remote_board_id] = [1, 2, 3];
        console.log("still working");
      });
    });
    console.log(cardsSkull);
    // assign and ready to go
    return Object.assign({}, state, {
      selectedDashboardData: action.payload,
      cards: cardsSkull
    });
  }
// more code
return state;
}

当我console.log(cardsSkull)一切正常时。

enter image description here

我希望cards在填充后具有cardsSkull的值,但实际输出是一个空数组

2 个答案:

答案 0 :(得分:2)

您将cardsSkull定义为数组(这是一个内部对象),但是由于idLis不是数字,因此cardsSkull[idLis] = {};不会在数组的数组部分内填充元素对象,而是数组对象本身内的一个元素。 因此,在屏幕快照中,数组的length属性仍为0将数字用于idLis,问题就解决了。

答案 1 :(得分:1)

似乎您假设卡的类型错误,它是一个对象而不是数组。我建议更新如下

export default function dashboards(state: any = dashboardsState, action: any) {
  // more code
  if (action.type === Types.LOAD_DASHBOARD_SUCCESS) {
    // create the cards holder in the store
    const cardsSkull = Object.keys(action.payload.lists).reduce(
      (acc, idLis) => ({ ...acc, [idList]: {} }),
      {}
    );    

    action.payload.importedDashboards.forEach((impDash: any) => {
      Object.keys(impDash.mappedLists).forEach((key: any) => {
        const mpList = impDash.mappedLists[key];
        cardsSkull[mpList.idlistLocal][impDash.remote_board_id] = [1, 2, 3];
        console.log('still working');
      });
    });
    console.log(cardsSkull);
    // assign and ready to go
    return {
      ...state,
      selectedDashboardData: action.payload,
      cards: cardsSkull
    }
  }
  // more code
  return state;
}