Javascript 反应时循环体系结构

Javascript 反应时循环体系结构,javascript,reactjs,render,Javascript,Reactjs,Render,我正在尝试使用react语音识别创建一个语音监听器。我让它听,把短语孤立起来。它附带了一些命令startListening、stopListening、finalTranscript、interimTranscript和resetTranscript。我有它的工作,我可以点击一个按钮,它听,点击另一个按钮,它停止,点击复位,它复位。interimTranscript基本上是它对单词的第一次猜测,然后在一瞬间确定它会变成finalTranscript。这就是我的问题所在。基本流程是,有一个带有两个

我正在尝试使用react语音识别创建一个语音监听器。我让它听,把短语孤立起来。它附带了一些命令startListening、stopListening、finalTranscript、interimTranscript和resetTranscript。我有它的工作,我可以点击一个按钮,它听,点击另一个按钮,它停止,点击复位,它复位。interimTranscript基本上是它对单词的第一次猜测,然后在一瞬间确定它会变成finalTranscript。这就是我的问题所在。基本流程是,有一个带有两个值的范围滑块,当移动它时,它会触发调用此函数的onChange处理程序。startListening()

然后在我的呈现中,我有一个if语句,它检测短语从interimTranscript到finalTranscript的时刻

  render(){
    if(this.props.finalTranscript){
      this.sendCommand();
    }
  sendCommand(){
    console.log("send command", this.props.finalTranscript);
    this.props.resetTranscript;
  }
其中一个问题是,finalTranscript将继续将所有不同的最终成绩单添加到一个长字符串中。所以我可以说“hello”send命令打印“hello”,然后我说“bye”,send命令打印“hello bye”,但是sendcommand()对于每个单词都会触发一次。因此,我将按sendCommand()两次。我用resetTranscript清除了finalTranscript,解决了这个问题

  render(){
    if(this.props.finalTranscript){
      this.sendCommand();
    }
  sendCommand(){
    console.log("send command", this.props.finalTranscript);
    this.props.resetTranscript;
  }
但是,我得到一个错误,告诉我不应该通过render函数使用this.props.resetTranscript。我尝试在我的句柄更改中创建一个while循环,但总是陷入无限循环中。创建while循环以启动语音侦听器、触发最终转录后的post、用resetTranscript清除finalTranscript并返回听力,什么是一个好方法

Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

正如错误所述,渲染方法应该只是纯函数。这意味着返回一个从您的状态和道具派生的视图,而不是引发状态更改。更不用说,如果不小心,可能会导致无限渲染。如果要执行这些效果,例如如果
this.props.finalTranscript
是truthy(或不是空的),请发送命令。在生命周期方法中这样做

componentDidUpdate(){
 if(this.props.finalTranscript){
  this.sendCommand()
 }
}
我假设您使用的是类组件。如果您想使用钩子,请查看如何使用
useffect