我需要将数组中的第一个元素作为最后一个元素。
问题是它是指向该对象的链接。
如何使用不变性助手来做到这一点。
我现有的代码如下。
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()
。
如何做得更好?
最佳答案
我不知道immutability.js
,但为此目的,您可以使用reduceRight
,它是标准库中的纯函数
,如下:
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 }, []);}
关于javascript - 如何使用 Immutability Helpers 推送数组中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45120830/