【问题标题】:My React button click logs twice for every single click每次单击,我的 React 按钮单击记录两次
【发布时间】:2020-08-03 11:46:00
【问题描述】:

Image of my log

每当我单击子组件中的按钮时,每次单击都会记录两次。我通过在我的子组件渲染函数中简单地添加一个 console.log(this.props) 发现了这一点。这是下面的代码

父组件

import React, { Component } from "react";
import Counter from "./counter";

class Counters extends Component {
  constructor(props) {
    super(props);

    this.state = {
      value: 0,

    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({ value: this.state.value + 1 });
  }
  render() {
    return (
      <div>
        <Counter onClick={this.handleClick} value={this.state.value} />
      </div>
    );
  }
}

export default Counters;

子组件

import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";

class Counter extends Component {
  render() {
    console.log(this.props);
    return (
      <div className="container">
        <span className="badge badge-secondary">{this.props.value}</span>
        <button
          onClick={this.props.onClick}
          type="button"
          className="btn btn-primary m-2"
        >
          Increment
        </button>
      </div>
    );
  }
}

export default Counter;

【问题讨论】:

  • 添加您的代码,以便我们为您提供帮助。
  • 欢迎来到堆栈溢出。您需要发布代码以便我们为您提供帮助!我们还能怎么判断问题是什么?
  • 只是为了检查,你能把onClick道具命名改成handleClick之类的东西吗?
  • 我非常怀疑点击处理程序被调用了两次。我认为状态更新更有可能导致重新渲染,并且由于您的 console.log()render 函数中,道具只是被记录了两次。如果将console.log() 移至handleClick 函数,您会看到多少日志?
  • @rickdenhaan 当我将它放在handleClick函数中时它不会记录两次,但是为什么渲染函数会渲染两次

标签: reactjs


【解决方案1】:

这是因为您的应用包含在 &lt;React.StrictMode&gt; 中,这可能会导致渲染函数或功能组件被多次调用以进行调试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 2022-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 2011-01-08
    相关资源
    最近更新 更多