将变量传递给 setState

Passing Variable to setState

我是新手。在我的程序中,要求用户点击一个按钮,根据那个按钮,改变状态。

这是渲染部分:

<button onClick={this.togglePage(2)}>Click Here</button>

这是之前的部分:

  constructor(props) {
    super(props);
    this.togglePage = this.togglePage.bind(this);

    this.state = {
      currentpage: 1,
    };
  }
  togglePage(page) {
    this.setState({
      currentpage: page,
    });
  }

我在这里传递值的方式是否正确?我收到一条错误消息 "Maximum Update Depth Exceeded"

您需要传递一个函数,而不是立即调用它

 <button onClick={() => this.togglePage(2)}>Click Here</button>

正如目前所写,您在渲染中调用 togglePage,这会导致状态更新并重新渲染调用堆栈。

另一种方法是不将其绑定在构造函数中,而是将其绑定在按钮标记中,如下所示,

<button onClick={this.togglePage.bind(this,2)}>Click Here</button>