【问题标题】:onClick() causing a Maximum update depth exceeded erroronClick() 导致最大更新深度超出错误
【发布时间】:2021-06-30 23:30:06
【问题描述】:

在render方法中,为什么不喜欢onClick属性中的this.increment?我不确定最大更新深度误差是如何关联的。抱歉,我是新来的反应,找不到太多关于此的文档。

import React, { Component } from 'react'

class Counter extends Component {
    constructor(props) {
        super(props)

        this.state = {
            count: 0
        }
    }

    increment() {
        this.setState(
            {
                count: this.state.count + 1
            },
            () => {
                console.log('Callback value', this.state.count)
            }
        )
    }

    render() {
        return (
            <div>
                <div> Count - {this.state.count}</div>
                <button onClick={this.increment()}> Increment </button>
            </div>
        )
    }

}
export default Counter

【问题讨论】:

  • 将此onClick={this.increment()} 更改为onClick={this.increment} 应该可以解决它

标签: reactjs


【解决方案1】:

你需要让onClick引用this.increment而不是调用它。

要解决此问题,请执行此操作 onClick={this.increment}onClick={() =&gt; this.increment}。我还建议您在official documentation 中快速阅读Event Handling

【讨论】:

    【解决方案2】:

    onClick={this.increment()}onClick={this.increment}。您必须在 onclick 上引用指向该函数的指针。

    【讨论】:

      猜你喜欢
      • 2020-07-15
      • 1970-01-01
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多