刚开始学react没多久,现在边干活边学习,今天遇到了一个bug,百度了一下解决了,总结一下
当我写下面这段代码的时候,遇到了这个bug,f12之后发现,无限报警告
代码:<a href = "#" onClick={this.handleShow(true)}>显示</a>
警告: .Warning: setState(...): Cannot update during an existing state transition (such as within render
or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount
。
通过百度后得知,原来react调用render方法渲染超链接的时候,props发生了改变,即this.handleShow直接执行了,因为render会通过props或者states改变来重新渲染,即DOM diff,所以结果变成了render——>组件——>props/states改变——>render的死循环中。
解决方法:通过匿名箭头函数即可解决,这样在render渲染的时候,props或者states也不会发生改变。
代码:<a href = "#" onClick={()=>this.handleShow(true)}></a>