【问题标题】:What are the difference between the React codes below? Which one is most efficient or effective? Or are they practically the same?下面的 React 代码有什么区别?哪一种最有效或最有效?或者它们实际上是一样的?
【发布时间】:2019-11-08 03:24:37
【问题描述】:

我目前正在进行一个项目,想出了两组不同的代码,想知道两者之间是否存在差异。

ReactJS(最新版本)

1.

columns.map(v => v.aggregate = (values) => values[0]);

2.

columns = columns.map( v => ({ 
            ...v,
            aggregate : (values) => values[0]
        }))

预期结果:

const columns = [
    {
        Header: 'ID',
        accessor: 'empid',
        shown: true,
        width: 130
    }, {
        Header: 'Name',
        accessor: 'name',
        shown: true,
        aggregate: (values) => values[0],
        width: 130
    }, {
        Header: 'Age',
        accessor: 'age',
        shown: true,
        aggregate: (values) => values[0],
    }, {
        Header: 'Email',
        accessor: 'email',
        shown: true,
        aggregate: (values) => values[0],
        width: 150
    },  {
        Header: 'Birthday',
        accessor: 'birthday',
        shown: true,
        aggregate: (values) => values[0],
        width: 150
    }
];

我将把它添加到 ReactTable 组件中,并通过 id 聚合透视。

【问题讨论】:

  • 一个改变数组中的现有对象,另一个不改变
  • 感谢@CertainPerformance 的回复!

标签: javascript arrays reactjs object ecmascript-6


【解决方案1】:

在第一个示例中,您直接对每个对象进行变异。在第二个示例中,您首先使用扩展运算符,因此您首先对每个对象进行浅层复制,而不是直接对其进行变异。

【讨论】:

  • 感谢@JackBashford 的回复!
  • 鉴于预期的输出,这两种方法会做同样的事情而没有问题吗?性能或效率如何?
  • 第二个效率较低,因为它复制对象 - 因此对于非常大的数组(数千个),您最好使用第一个选项。
  • 太棒了!再次感谢先生。上帝保佑你!
  • @randyk69 为了提高效率,您不应该在不想创建新数组时使用map。只需编写一个for (const v of columns) 循环。为了提高效率,不要重新创建许多函数,只需将相同的函数分配给所有对象:function aggregate(values) { return values[0] } for (const v of columns) v.aggregate = aggregate;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
相关资源
最近更新 更多