对象没有传递给另一个方法(反应)

object didnt get passed to another method (React)

我目前正在学习 React 并遵循视频教程,但我遇到了一个无法传递给另一个方法的对象,但是当我传递一个 ID 时它工作正常

这是方法

handleIncrement = (product) => {
    console.log(product);
    this.setState({ count: this.state.count + 1 });   
};

这是我尝试传递的方法

render() {
    return (
      <div>
        <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
        <button
          onClick={this.handleIncrement({ id: 1 })}
          className="btn btn-secondary btn-sm"
        >
          Increment
        </button>
      </div>
    );

产品 onClick={this.handleIncrement(product)} 错误为未定义

src\components\counter.jsx
  Line 19:47:  'product' is not defined  no-undef

但如果我使用 onClick={() => this.handleIncrement({ id:1 })} 它工作得很好,而且当我使用 onClick={(product) => this.handleIncrement(product)}

时也能工作

onClick 事件处理程序必须是函数,而不是函数调用。这就是为什么您提供的示例 onClick={() => this.handleIncrement({ id:1 })} 可以正常工作,因为这是一个匿名函数,而您调用该函数的示例不起作用。

你遇到的问题是

onClick={this.handleIncrement({ id: 1 })}

这是 ReactJS 新手通常的困惑,但这是一般的经验法则,你有两种方法

  1. 如果您的函数没有预期 parameter
funcWithoutParam = () => {
  console.log('hi')
}; 
onClick={this.funcWithoutParam}
  1. 如果您的函数需要 parameter
handleIncrement = (param) => {
  console.log(param)
}

onClick={() => this.handleIncrement({ id: 1 })}