2017-07-15 5 views
0

配列の最初の要素を最後にプッシュする必要があります。不変のヘルパーで配列の最初の要素を押す方法

問題は、オブジェクトへのリンクです。

不変のヘルパーで行う方法。

私の既存のコードは以下の通りです。私は不変ヘルパーを持って何

state = { 
 

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

 

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

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

 
    this.setState({ table: newTable }); 
 
    
 

 
}

私は再びslice()を使用するので、私は

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

良くない示唆しています。

これを行うにはどうすればよいですか?

答えて

0

私は約immutability.jsを知らないが、以下のように、この目的のために、あなたは、標準ライブラリからpure functionです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 }, []);} 
関連する問題