React setState不更新状态;没有调用回调

时间:2017-12-07 22:02:07

标签: javascript reactjs web-audio setstate

我正在尝试使用"Tale of Two Clocks" tutorial之后构建的节拍器将其转换为简单的React项目。我认为将节拍器的参数(节奏,音符分割等)映射起来很简单,然后对它进行扩展以构建一个步进音序器(对技术来说很好!)。那就是说,我遇到了一个特定的问题,我想知道为什么。

我在Metronome组件上有很多显着的部分,如下所示:

import React from 'react'

class Metronome extends React.Component {
  constructor (props) {
    super(props)

    this.audioContext = new (window.AudioContext || window.webkitAudioContext)()

    this.state = {
      tempo: 120.0,
      noteResolution: 0,
      isPlaying: false,
      current16thNote: 0,
      gateLength: 0.05,
      noteLength: 0.25,
      nextNoteTime: 0.0
    }

    this.lookahead = 0.1
    this.schedulerInterval = 25.0
    this.timerID = null

    this.updateStartStopText = this.updateStartStopText.bind(this)
    this.play = this.play.bind(this)
    this.scheduler = this.scheduler.bind(this)
    this.scheduleNote = this.scheduleNote.bind(this)
    this.nextNote = this.nextNote.bind(this)
  }

  updateStartStopText () {
    return this.state.isPlaying ? 'Stop' : 'Start'
  }

  play () {
    this.setState({ isPlaying: !this.state.isPlaying }, () => {
      if (this.state.isPlaying) {
        this.setState({ current16thNote: 0 }, () => {
          this.setState({
            nextNoteTime: this.audioContext.currentTime
          }, this.scheduler)
        })
      } else {
        window.clearTimeout(this.timerID)
      }
    })
  }

  scheduler () {
    while (this.state.nextNoteTime < this.audioContext.currentTime + this.lookahead) {
      this.scheduleNote(this.state.current16thNote, this.state.nextNoteTime)
      this.nextNote()
    }

    this.timerID = window.setTimeout(this.scheduler, this.schedulerInterval)
  }

  scheduleNote (beatNumber, time) {
    if ((this.state.noteResolution === 1) && (beatNumber % 2)) {
      return
    } else if ((this.state.noteResolution === 2) && (beatNumber % 4)) {
      return
    }
    const osc = this.audioContext.createOscillator()
    osc.connect(this.audioContext.destination)
    if (!(beatNumber % 16)) {
      osc.frequency.value = 220
    } else if (beatNumber % 4) {
      osc.frequency.value = 440
    } else {
      osc.frequency.value = 880
    }

    osc.start(time)
    osc.stop(time + this.state.gateLength)
  }

  nextNote () {
    var secondsPerBeat = 60.0 / this.state.tempo
    let nextTime = this.state.nextNoteTime + (secondsPerBeat * this.state.noteLength)

    this.setState({
      nextNoteTime: nextTime,
      current16thNote: (this.state.current16thNote + 1)
    }, () => {
      if (this.state.current16thNote === 16) {
        this.setState({ current16thNote: 0 })
      }
    })
  }

  render () {
    return (
      <div>
        Metronome

        <button type='button' onClick={this.play}>{this.updateStartStopText()}</button>
      </div>
    )
  }
}

export default Metronome

或多或少的一切都像你对React所期望的那样,通过this.setState()调用来交换vanilla JS变量重新分配/递增,。在很多情况下,我需要使用状态中的更新值进行计算,并且知道setState()是异步的并且经常批量调用,我在很大程度上依赖于setState采用的可选回调。

事情似乎出错的地方是nextNote()方法。状态永远不会正确更新:this.state.nextNoteTime永远不会获得超出play()方法中指定值的更新值。代码原样永远不会进入传递给setState()的回调nextNote()。如果我从组件的状态中删除nextNoteTime并将其保存为组件上的属性,手动更新并跟踪其值,节拍器似乎按预期工作,即我的节拍器在vanilla JS中的最终状态。从技术上讲,这是成功的,但不是我正在寻找的答案。

我尝试使用Promises,我尝试使用React组件API(componentWillUpdateshouldComponentUpdate等)来确定下一个状态是否是我正在寻找的状态。但超过某一点(如scheduler()方法的3次递归调用),while循环变得混乱,因为this.state.nextNoteTime永远不会增加。尔加!

思想?

1 个答案:

答案 0 :(得分:0)

我认为这是因为你嵌套了setState s。

请尝试以下播放方法。

play() {
  const { isPlaying } = this.state;
  const newState = { isPlaying: !isPlaying };
  if (!isPlaying) {
    Object.assign(newState, {
      current16thNote: 0,
      nextNoteTime: this.audioContext.currentTime
    });
  }

  this.setState(newState, (...args) => {
    if (!isPlaying) {
      this.scheduler(...args);
    } else {
      window.clearTimeout(this.timerID)
    }
  });
}

同时删除setState的{​​{1}}嵌套。