簡體   English   中英

當React.js中顯示模式時如何做?

[英]How to do something when modal is shown in React.js?

我正在使用react.jsreduxredux-modal 我想在顯示模態時執行代碼。

當我將代碼放入componentWillMount ,它只是在第一次執行。

  componentWillMount() {
    // Just execute one time
    // Do something
  }

redux-modal使用show state變量顯示或隱藏modal,因此我使用以下代碼來處理show事件:

  componentWillReceiveProps(nextProps) {
    // When modal is shown
    if (!this.props.show && nextProps.show) {
       // Do something
    }
  }

除了第一次安裝模態外,它運行良好。

現在,我一起使用componentWillMountcomponentWillReceiveProps來處理模式展示事件。

有沒有更好的解決方案來處理模態表演事件?

您可以簡單地將代碼放入渲染函數中,如下所示:

render() {
  {(this.props.show) ? <MyModalComponent/> : null}
  ... // other components to render
}

如果您使用componentDidMount()觸發API調用,那么使用上面的代碼,您的流程將是:

  • 第一次渲染: this.props.show == false
  • 運行render() ,組件將呈現無模式
  • componentDidMount()運行,從而觸發API調用
  • API調用更新存儲的結果,將show設置為true
  • 商店更新觸發新的渲染周期
  • 下一個渲染周期: this.props.show == true
  • 運行render() ,組件將被模態渲染
  • componentDidMount()未運行,因為這是第二個渲染)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM