ReactJS: Hiding a text produces an error: Maximum update depth exceeded

ReactJS: Hiding a text produces an error: Maximum update depth exceeded

我无法使用 class 表单中的按钮隐藏我的文本(页眉)。我在下面尝试此代码:

constructor(props){
  super(props)
  this.state = {
    showHeader: true,
  }
}

然后我使用 setState 呈现上面的状态:

render () {
  return (
    <div>
      {this.state.showHeader && <Header /> }
      <button onClick={ this.setState({showHeader: false})} >Hide</button>
    </div>

我知道这是一个愚蠢的问题,但我无法帮助自己,因为我是一个完全的初学者。但我是用函数做的,我只是想尝试使用 class 来转换它。这是我使用函数所做的:

const [show, setShow] = React.useState(true);
const hideHeader = () => {
  setShow(!show)
}

和return这个:

 return (
    <div>
      {show && <Header />}
      <button onClick={hideHeader}>Hide Header</button>
    </div>
  )

现在您正在渲染函数中调用 setState()。这会导致问题,因为 setState 导致调用您的 render 方法,如果您的渲染方法直接调用 setState,您将陷入循环。

您需要做的是在事件处理程序中调用它:

// bad
onClick={this.setState({showHeader: false})}
// good
onClick={() => this.setState({showHeader: false})}

因此您的按钮应如下所示:

<button onClick={() => this.setState({showHeader: false})} >Hide</button>

来自the docs

The render() function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.