2017-01-01 3 views
1

저는 React에 상당히 익숙하며 드럼 머신을 구축하려고합니다. 나는 완전히 붙이게된다. 셀 배열을 통해 루프 및 true로 부울 업데이트하려고하지만 각 상태 업데이트 사이에 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를 사용해야하며 타이머 콜백의 컨텍스트에서 상태에 대한 액세스가 더 이상 존재하지 않아야합니다. 또한 각 셀에 대해 별도의 지연된 간격을 생성합니다. 상태를 단일 지연 기능으로 설정하는 것이 좋습니다.

이것은 테스트되지 않았지만 올바른 방향으로 가리켜 야합니다. 배열 slice가 수정 된 배열의 복사본을 만든 다음 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;