【问题标题】:insert/update object in array using index when array is empty in redux react当redux中的数组为空时,使用索引在数组中插入/更新对象
【发布时间】:2021-11-13 03:44:01
【问题描述】:

我正在做一个 react 项目并使用 redux 进行状态管理。我想使用索引更新数组中的值,但最初数组是空的。

我该怎么做?

我正在这样做:

case Actions.UPDATE:
      return {
        ...state,
        defaultCodeList: state.defaultCodeList.map((code, index) => (index === action.index ? {
          code_sys_id: state.masterName, code_sys_cat_id: state.codeSystem, [`${state.codeSystem}_description`]: action.description,
        } : codeset)),
      };

最初defaultCodeList:[] 并在按下按钮时触发此操作。 当索引匹配时,我想将上述对象放在该特定索引上。

这方面有什么线索吗?

【问题讨论】:

    标签: javascript arrays reactjs redux react-redux


    【解决方案1】:

    创建一个新数组,将数组的索引设置为与操作的索引相同的对象值。这会将所有其他索引设置为未定义。然后,您现在可以将数组中的未定义值设置为codeset,然后将其分配给defaultCodeList

    case Actions.UPDATE:
        const newDefaultCodeList = [...state.defaultCodeList];
        newDefaultCodeList[action.index] = {
            code_sys_id: state.masterName, code_sys_cat_id: state.codeSystem, [`${state.codeSystem}_description`]: action.description,
        } // this sets the remaining values at other indexes to undefined
        return {
            ...state,
            defaultCodeList: newDefaultCodeList.map((code, index) => (index !== action.index && codeset)),
        };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2019-07-30
      相关资源
      最近更新 更多