纯渲染和按钮onClick内联setStates

当谈论React中的纯渲染方法以及渲染内部的设置状态是如何构成严重的反模式时,我们在此方面的严格程度如何?我得到的是,如果我在渲染函数中执行setState,而该函数不需要任何用户输入,则它可以创建无限循环并重新渲染。

我不明白的是,在编写接收来自用户输入的页面元素时,此规则也适用吗?我的意思是,这两种为按钮编写简单的单击处理程序的方式有什么区别:

render() {
  return(
    <div className="container-fluid info-modal">
      <div className="row">
        <div className="col col-12">
          <InfoModal active={this.state.modalActive}>
            <h2>Fine dining recipes</h2>
            <p>Here you can publish your fine dining recipes. Don't forget to 
            include every ingredient needed!</p>
            <Button
              title="ok"
              onClick={() => {
                this.setState({ modalActive: false })
              }}
            />
          </InfoModal>
        </div>
      </div>
    </div>
  )
} 

render() {
  return(
  <div className="container-fluid info-modal">
    <div className="row">
    <div className="col col-12">
      <InfoModal active={this.state.modalActive}>
      <h2>Fine dining recipes</h2>
      <p>Here you can publish your fine dining recipes. Don't forget to 
      include every ingredient needed!</p>
      <Button
              title="ok"
              onClick={() => {
                this.closeModal()
              }}
      />
      </InfoModal>
    </div>
    </div>
  </div>  
  )
}

我知道对于更复杂的组件,执行此操作的正确方法可能是使用此类接收的单击处理程序作为属性,但是对于简单的用例,在内部设置状态确实有一些具体的危害。内联点击处理程序?

评论
  • 笑伴孤单
    笑伴孤单 回复

    When docs say that you must not setState within render it means that that the setState function must not be called as soon as we render and not that setState cannot be written inside render

    所以当你写

     <Button
          title="ok"
          onClick={() => {
             this.setState({ modalActive: false })
         }}
     />
    

    You are not actually calling setState in render but you are calling it on click action of button which are 2 different things

    所以不管你写

     <Button
          title="ok"
          onClick={() => {
              this.closeModal()
          }}
      />
    

    要么

    <Button
        title="ok"
        onClick={() => {
            this.setState({ modalActive: false })
        }}
     />
    

    are equivalent if you just setState inside closeModal

    以下是无法接受的通话

    <Button
          title="ok"
          onClick={this.setState({ modalActive: false })}
     />