等待来自非反应源的请求,在反应组件内部

时间:2019-07-18 19:28:03

标签: javascript reactjs

我已经在我的react组件中使用了calendly API

我尝试使用以下代码:

import React, { Component } from 'react'
import FullScreenModal from '../../../UIComponents/FullScreenModal'

export default class MeetingBooking extends Component {


    state={
        isLoading: false
    }
componentDidMount() {
    console.log(this.state.isLoading)
    const head = document.querySelector('head');
    const script = document.createElement('script');
    script.setAttribute('src',  'https://assets.calendly.com/assets/external/widget.js');
    head.appendChild(script);
    this.setState({loading: false})
}


    render() {
        console.log(this.state.isLoading)
        return (
            <FullScreenModal open={this.props.open} title={"Book a Meeting"} handleClose={this.props.handleClose}>
            {this.state.isLoading ?
            <p>Loading...!!!!</p> : 
            <div
             className="calendly-inline-widget" 
             data-url="https://calendly.com/kristofferlocktolboll"
             style={{minWidth: '320px', height: '580px'}}>
             </div> 
            }
             </FullScreenModal>

        )
    }
}

问题在于,我无法像使用Axiosfetch API请求那样,等待来自URL的请求,因此无论何时插入脚本,加载组件都不会如图所示。

所以我正在寻找一种方法来监听注入的javascript并等待它,因此我可以同时展示我的<p>Loading....!!!!</p>,这可以实现吗?

2 个答案:

答案 0 :(得分:2)

您可以向load元素添加<script>事件侦听器,下面是一个示例:

export default class MeetingBooking extends Component {

  state = {
    isLoading: false
  }

  componentDidMount() {
    this.setState({ isLoading: true }, () => {
      const script = document.createElement('script');
      script.type = 'text/javascript';

      script.onload = () => this.setState({ isLoading: false });

      script.src = 'https://assets.calendly.com/assets/external/widget.js';
      document.head.appendChild(script);
    });
  }
}

答案 1 :(得分:0)

import React, { Component } from 'react'
import FullScreenModal from '../../../UIComponents/FullScreenModal'

export default class MeetingBooking extends Component {


    state={
        isLoading: true
    }
async componentDidMount() {
   if (this.state.isLoading) {
    const head = document.querySelector('head');
    const script = document.createElement("script");
    script.src = 'https://assets.calendly.com/assets/external/widget.js';
    script.async = true;
    head.appendChild(script);
    await this.setState({loading: false})
  }
}


    render() {
        console.log(this.state.isLoading)
        return (
            <FullScreenModal open={this.props.open} title={"Book a Meeting"} handleClose={this.props.handleClose}>
            {this.state.isLoading ?
            <p>Loading...!!!!</p> : 
            <div
             className="calendly-inline-widget" 
             data-url="https://calendly.com/kristofferlocktolboll"
             style={{minWidth: '320px', height: '580px'}}>
             </div> 
            }
             </FullScreenModal>

        )
    }
}