美文网首页
React 页面加载后自动执行onClick事件

React 页面加载后自动执行onClick事件

作者: BlinglingSam | 来源:发表于2019-10-12 15:26 被阅读0次

    报错: Warning: Cannot update during an existing state transition (such as within render)

     <Button className={placeTime.length > 1 ? styles.delBtn : styles.delFirst} 
                      onClick={this.onRemove (index)}>
      <Icon type={'delete'}/>删除
    </Button>
    )
    
    
     onRemove = (index) => {
        const { placeTime } = this.state
        console.log(placeTime, index);
        placeTime.splice(index, 1)
        this.setState({
          placeTime
        })
      }
    

    删除按钮绑定的onRemove点击事件,想要带着参数index去执行,但这种操作是不允许的,刚好在事件函数中也有setState操作,这样就会陷入到死循环中,不停的改变state,render()又不停的被执行。

    解决方案

    // 一
     <Button className={placeTime.length > 1 ? styles.delBtn : styles.delFirst} 
                      onClick={()=>this.onRemove (index)}>
      <Icon type={'delete'}/>删除
    </Button>
    // 二
     <Button className={placeTime.length > 1 ? styles.delBtn : styles.delFirst} 
                      onClick={this.onRemove .bind(this,index)}>
          <Icon type={'delete'}/>删除
        </Button>
    
    

    相关文章

      网友评论

          本文标题:React 页面加载后自动执行onClick事件

          本文链接:https://www.haomeiwen.com/subject/bdbqmctx.html