HTML script is loading AFTER react components

前端 未结 2 773
孤城傲影
孤城傲影 2021-01-06 01:50

My index.html



    

        
        

        
相关标签:
2条回答
  • 2021-01-06 02:03

    My suggestions:

    Change your google API script tag to be this, where you remove async and defer

    <script src="https://apis.google.com/js/client:platform.js"></script>
    

    Get rid of your start function, which will now run the console.log fine and dandy, but the second bit of code will cause the same issue as it will also be running asynchronously.

    Modify your react code, so that the componentWillMount calls the contents of that function instead:

    componentWillMount() {
      gapi.load('auth2', () => {
        auth2 = gapi.auth2.init({
          client_id: 'urhaxorid.apps.googleusercontent.com',
          scope: 'profile email',
          onLoad: () => {
            this.setState({ mapLoaded: true });
          }
        });
      });
    }
    
    componentDidMount() {
      if (this.state.mapLoaded) {
        console.log(gapi.auth2.getAuthInstance());
      }
    }
    

    Please bear in mind that I don't know what the onLoad is for google apis, and I am not 100% sure how to best do the setState stuff, but it may be a starting block.

    0 讨论(0)
  • 2021-01-06 02:04

    I think the best way to load scripts in react is with a container component. It's a pretty simple component and it allows to you write the logic for importing the script in a component rather than your index.html. You are also going to want to make sure you don't include the script more than once by calling loadScript after a check in componentDidMount.

    This is adapted from: https://www.fullstackreact.com/articles/how-to-write-a-google-maps-react-component/

    Something like this. . .

      componentDidMount() {
        if (!window.google) {
          this.loadMapScript();
        }
        else if (!window.google.maps) {
          this.loadMapScript();
        }
        else {
          this.setState({ apiLoaded: true })
        }
      }
    
      loadMapScript() {
        // Load the google maps api script when the component is mounted.
    
        loadScript('https://maps.googleapis.com/maps/api/js?key=YOUR_KEY')
          .then((script) => {
            // Grab the script object in case it is ever needed.
            this.mapScript = script;
            this.setState({ apiLoaded: true });
          })
          .catch((err: Error) => {
            console.error(err.message);
          });
      }
    
      render() {
        return (
          <div className={this.props.className}>
            {this.state.apiLoaded ? (
              <Map
                zoom={10}
                position={{ lat: 43.0795, lng: -75.7507 }}
              />
            ) : (
              <LoadingCircle />
            )}
          </div>
        );
      }
    

    and then in a separate file:

    const loadScript = (url) => new Promise((resolve, reject) => {
      let ready = false;
      if (!document) {
        reject(new Error('Document was not defined'));
      }
      const tag = document.getElementsByTagName('script')[0];
      const script = document.createElement('script');
    
      script.type = 'text/javascript';
      script.src = url;
      script.async = true;
      script.onreadystatechange = () => {
        if (!ready && (!this.readyState || this.readyState === 'complete')) {
          ready = true;
          resolve(script);
        }
      };
      script.onload = script.onreadystatechange;
    
      script.onerror = (msg) => {
        console.log(msg);
        reject(new Error('Error loading script.'));
      };
    
      script.onabort = (msg) => {
        console.log(msg);
        reject(new Error('Script loading aboirted.'));
      };
    
      if (tag.parentNode != null) {
        tag.parentNode.insertBefore(script, tag);
      }
    });
    
    
    export default loadScript;
    

    I know it's a lot but when I was first doing this it was so relieving when I found out there was a (fairly) simple way of including any script in any react component.

    Edit: Some of this I just copy pasted but if you aren't using create-react-app you will probably have to replace some of the ES6 syntax.

    0 讨论(0)
提交回复
热议问题