【问题标题】:How to push first element in array with Immutability Helpers如何使用不变性助手推送数组中的第一个元素
【发布时间】:2017-07-15 17:14:03
【问题描述】:

我需要将数组中的第一个元素作为最后一个。

问题在于它是指向对象的链接。

如何使用不变性助手来做到这一点。

我现有的代码如下。

state = {

    table: [['', '', '', ''],
            ['', '', '', ''],
            ['', '', '', ''],
            ['', '', '', '']],
  }


appendRow = () => {
    
    let newTable = deepcopy(this.state.table);

    newTable.push(this.state.table[0].slice())

    this.setState({ table: newTable });
    

}

我对不变性助手的建议不好

 appendRow = () => {
    this.setState({ table: update(this.state.table, { $push: [this.state.table[0].slice()] }) });
  }

因为我再次使用slice()

如何做得更好?

【问题讨论】:

    标签: javascript reactjs immutability immutable.js


    【解决方案1】:

    我不知道immutability.js,但为此您可以使用reduceRight,它是标准库中的pure function,如下所示:

    table.reduceRight((a,e,i) => { i === 0 ? a.push(e) : a.unshift(e); return a }, []);
    

    在你的例子中插入这个:

    appendRow = () => {
        this.state.table.reduceRight((a,e,i) => { i === 0 ? a.push(e) : a.unshift(e); return a }, []);}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 2017-06-03
      • 1970-01-01
      • 2020-12-22
      • 2018-06-12
      • 1970-01-01
      • 2020-05-12
      相关资源
      最近更新 更多