onClick处理程序在每个渲染周期中触发 [英] onClick handler is triggered on each render cycle
问题描述
我有这样的默认状态
this.state = {
selectedTab : 'tab1'
}
然后
我的渲染方法像这样
render(){
const { selectedTab } = this.state;
return(
<li>tab1</li><li>tab2</li>
<div id="content">
{selectedTab == 'tab1' ? this.renderTab1Content() : this.renderTab2Content()}
</div>
)
}
一切都在上面工作。但是我没有使用点击事件来实现切换选项卡。
Everything worked above. But I failed to implement switch tab using click event.
我试图在我的 li
上绑定onclick事件来改变selectedTab的状态,但我得到了无限循环错误。像这样
I tried to bind onclick event on my li
to change the state of selectedTab, but I got infinity loop error. Like this
<li onClick={this.setState({selectedTab :'tab1'})}>Tab 1</li>
<li onClick={this.setState({selectedTab :'someothertab'})}>Tab 2/li>
为什么?
推荐答案
发生此错误是因为您 onClick
处理程序需要一个函数,但您已在事件上调用了一个setState语句,因此每次使用<$ c表示更改时$ c> setState ,再次调用渲染,因此 onClick
再次调用 setState
触发无限循环。您可以在 onClick
事件中使用箭头函数
或调用单独函数
This error happens because you onClick
handler expects a function but you have called a statement to setState on the event and hence everytime you state changes using setState
, the render is called again and hence the onClick
again calls the setState
which triggers an infinite loop. You can do this by using an arrow function
in onClick
event or calling a separate function
<li onClick={() => this.setState({selectedTab :'tab1'})}>Tab 1</li>
或
handleClick = () =>{
this.setState({selectedTab :'tab1'})
}
<li onClick={this.handleClick}>Tab 1</li>
这篇关于onClick处理程序在每个渲染周期中触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!