页面加载时打开模式,导致超出最大更新深度

时间:2019-04-04 16:41:49

标签: reactjs material-ui

我正在尝试在页面加载时打开模式,但得到Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

我知道为什么会这样,因为关于它的帖子很多。我不知道该如何解决。

我正在使用Material UI modal

我尝试将其加载到componentDidMount中-导致错误。我也尝试使用onClick并模拟一个单击以将其打开,但这不起作用-无法使模拟起作用。以下是我最近的尝试-引起的错误。

<Button onLoad={this.openModal.bind(this)()}>Open Modal</Button>

openModal(e) {
     this.setState({
      open:true
     })
  }

我似乎无法克服错误并在加载时打开模态。

模态文件中,模态本身如下所示:

 <Button onLoad={this.openModal.bind(this)()}>Open Modal</Button>
 <Modal
         aria-labelledby="simple-modal-title"
         aria-describedby="simple-modal-description"
         open={this.state.open}
         onClose={this.handleClose}
    >

在父组件中

   <Modal open={this.state.modalState}/> //=> true

我也尝试过此操作(事件处理程序已删除且未称为this.openModal.bind(this)())。出现错误

componentDidUpdate(){
  this.setState({
      open:this.props.open
    })
 }

1 个答案:

答案 0 :(得分:0)

通常,对于渲染模态,我们将使用状态来指定其打开或关闭状态。如果要在组件加载后立即打开模态,则可以将状态默认指定为true

例如

  Class Example extends React.component {
  construtor(props) {
  super(props)
 this.state = { open: true }
}
render() {
return <Modal open={this.state.open}>{//body goes here}</Modal>
}
}

默认情况下,这会打开模式,您可以根据需要进行切换

您正在setstate中调用componentdidupdate,而没有任何条件,这将导致堆栈级别太深的错误,因为在setstate之后,组件将被再次调用

如果需要,可以改用componentdidmount

相关问题