【问题标题】:Clone or duplicate object from array then push and rename using es6从数组中克隆或复制对象,然后使用 es6 推送和重命名
【发布时间】:2020-02-03 09:22:16
【问题描述】:

我想要一个列表组件,它可以编辑、复制或删除。 我已经选择要克隆的 id,但它没有推到项目旁边。 我正在使用 es6

这是我的代码

const [state, setState] = useState({
  formList: []
})

const handleDuplicateItem = id => {
  const duplicateSource = [...state.formList];
  const duplicateItem = duplicateSource.find(item => item.id !== id);
  duplicateSource.push(duplicateItem);

  setState({
    ...state,
    formList: [duplicateSource],
  });
};

<FormItemList
  dataSource={state.formList}
/>

【问题讨论】:

  • 你是什么意思“不推到项目旁边”?如果你的意思是重复的总是在数组的末尾,那就是 push 所做的
  • @jonrsharpe 例如,[1,1,2,3] 1 是克隆项。
  • 那么为什么要推呢?这总是添加到最后。看看例如developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

标签: javascript reactjs ecmascript-6


【解决方案1】:

您想要复制的项目旁边的副本(请注意,您现在有重复的 id,并且您无法在没有警告的情况下将数据映射到 jsx)。

你可以使用reduce来做到这一点:

const handleDuplicateItem = id => {
  setState({
    ...state,
    formList: state.formList.reduce((result, item) => {
      if (item.id === id) {
        //push an extra shallow copy of the item to result
        result.push({ ...item });
      }
      result.push(item);
      return result;
    }, []),
  });
};

【讨论】:

    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 2020-12-08
    • 2011-10-17
    • 2017-06-13
    • 2013-06-18
    相关资源
    最近更新 更多