2017-01-01 4 views
1

Reactにはかなり新しいですし、ドラムマシンを構築しようとしています。私は完全に立ち往生している。私は、セルの配列をループし、真にブール値を更新しようとしていますが、私は各状態の更新の間に2秒の遅延があるようにしています。ボタンをクリックすると、2秒後にアレイ全体が更新されます。ループを使ってタイムアウトを設定する方法について少しは読んだことがありますが、動作させることはできません。任意のアイデアの???React.js遅れのあるループ内の状態を更新する

import React from 'react' 

class Row extends React.Component{ 
    constructor(props){ 
    super(props) 
    this.tick = this.tick.bind(this); 
    this.delay = this.delay.bind(this); 
    this.state = { 
     cells: this.props.cell 
    } 
    } 

    tick(){ 
     this.state.cells.map((cell) => { 
     this.delay(cell) 
     }) 
    } 

    delay(cell){ 
    setInterval(() => { 
     cell.playing = true 
    },2000) 
    } 

    render(){ 
    return(
     <div> 
     <div>hello</div> 
     <button onClick={this.tick}>Click </button> 
     </div> 
    ) 
    } 
} 

export default Row; 

これは行コンポーネントです。少し早いですがお礼を!

答えて

0

状態を設定するにはsetStateを使用する必要があり、状態へのアクセスはタイマーコールバックのコンテキスト内に存在しなくなります。また、各セルごとに別々の遅延間隔を作成しています。状態を単一の遅延関数に設定するのが良いでしょう。

これは未テストですが、正しい方向を指すようにしてください。配列スライスが変更された配列のコピーを作成した後、setStateを使用してセルを更新することに注意してください。

import React from 'react' 

class Row extends React.Component{ 
    constructor(props){ 
    super(props) 
    this.tick = this.tick.bind(this); 
    this.delay = this.delay.bind(this); 
    this.state = { 
     cells: this.props.cell 
    } 
    } 

    tick(){ 
     this.delay(this.state.cells); 
    } 

    delay(cells){ 
    var that = this; 
    setInterval(() => { 
     var newCellState = cells.map((cell) => { 
      cell.playing = true 
     }); 
     that.setState({cells: newCellSate}); 
    },2000) 
    } 

    render(){ 
    return(
     <div> 
     <div>hello</div> 
     <button onClick={this.tick}>Click </button> 
     </div> 
    ) 
    } 
} 

export default Row; 
関連する問題