使用spread将我从API获得的对象添加到我的初始数据源中

问题描述 投票:1回答:1

我有一个初始数据源:

const initState = {
  columns: [
    {
      id: 'column-2',
      title: 'column-2',
      tabs: []
    }
  ],
  columnOrder: ['column-2']
};

一旦应用程序加载(这是我为自己构建的chrome扩展),我将从chrome中打开标签,并希望将它们作为新列添加到此数据源中。

这是我尝试这样做的:

export default (state = initState, action) => {
  switch (action.type) {
    case TABS_LOAD:
      return {
        columns: [
          { id: 'chromeTabs', title: 'chromeTabs', tabs: action.payload },
          ...state.columns
        ],
        columnOrder: [{"chromeTabs"}, ...state.columnOrder]
      };

    default:
      return state;
  }
};

我希望通过上面的函数创建一个像下面这样的数据对象:

const state = {
 columns: [
 {
      id: 'chromeTabs,
      title: 'chromeTabs',
      tabs: 
[tab1,tab2,tab3,tab4]
    }, 
    {
      id: 'column-2',
      title: 'column-2',
      tabs: []
    }
  ],
  columnOrder: ['chromeTabs', 'column-2']
}
};

不幸的是,这对我没用。我会很感激任何指示。

javascript ecmascript-6 redux spread-syntax
1个回答
2
投票

{"chromeTabs"}是语法错误。要添加到columnOrder数组,只需使用没有"chromeTabs"{}

return {
  columns: [
    { id: 'chromeTabs', title: 'chromeTabs', tabs: action.payload },
    ...state.columns
  ],
  columnOrder: ["chromeTabs", ...state.columnOrder]
  // No {} -----^-----------^
};

实例:

const initState = {
  columns: [
    {
      id: 'column-2',
      title: 'column-2',
      tabs: []
    }
  ],
  columnOrder: ['column-2']
};

const TABS_LOAD = "tabs-load";

const f = (state = initState, action) => {
  switch (action.type) {
    case TABS_LOAD:
      return {
        columns: [
          { id: 'chromeTabs', title: 'chromeTabs', tabs: action.payload },
          ...state.columns
        ],
        columnOrder: ["chromeTabs", ...state.columnOrder]
      };

    default:
      return state;
  }
};

console.log(f(initState, {type: TABS_LOAD}));
.as-console-wrapper {
  max-height: 100% !important;
}
© www.soinside.com 2019 - 2024. All rights reserved.