gpt4 book ai didi

javascript - React 成功执行了 onClick 函数,但未在 this.render 的其他部分执行

转载 作者:行者123 更新时间:2023-12-03 06:41:38 26 4
gpt4 key购买 nike

我有一个函数 stopRecording() ,我想在计时器用完或有人按下停止按钮时调用它。问题是,当计时器用完时(渲染函数的前半部分)调用它时,它会被连续调用,尽管我将它放在 if 子句中。当它作为按钮事件调用时(在渲染函数的返回部分),它可以正常工作。

注意我的控制台日志。当我在 Chrome 中打开控制台并让计时器耗尽时,我在代码正文中标记为成功的控制台日志会运行,但不会运行我用 //!!! 注释的日志。我还不断收到以下错误:Invariant Violation: setState(...): 在现有状态转换期间无法更新(例如在render内)。渲染方法应该是 props 和 state 的纯函数。

//...
stopRecording: function() {
if (this.state.recording){
console.log("this will log as expected")
this.setState({recordingStatus:"",
recording:false})
console.log("this will NOT log as expected'") //!!!
this.props.emit("recEmit")
}
}
render: function() {
var timeBar;
var countdown = "0";
var timeBarFill = "#FF9090"
if (this.state.recording){
countdown = new Date()-this.state.startTime
timeBarFill = "#FF3830";
if (countdown > this.state.maxRecLength){
console.log('this will log as expected')
countdown=0
this.stopRecording()
console.log('this will NOT log as expected') //!!!

};
}
//...
return(
//...
<button type="button" id="button" onClick={this.stopRecording}><b>Stop</b></button>
//...
)

最佳答案

您不应该永远render()内调用setState:https://github.com/facebook/react/issues/5591#issuecomment-161678219

渲染应该是组件的 props 和状态的函数,这意味着它不应该有任何副作用(例如更改其自身的状态)。

此外,您不能保证当倒计时即将到期时,React 会调用组件的 render() 方法。考虑在组件的生命周期方法中使用 setTimeout

关于javascript - React 成功执行了 onClick 函数,但未在 this.render 的其他部分执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37932121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com