简体   繁体   中英

React - correct way to wait for page load?

In React JS, what is the correct way to wait for a page to load before firing any code?

Scenario: A login service authenticates a user then redirects them (with a cookie), to a React App. The React App then straight away searches for a cookie and validates it against an endpoint.

But the problem I am getting is when user is authenticated at login service, then forwarded to React App, the App is loading so quick before cookie is even loaded.

What is the right way to fire the code? I tried wrapping in a componentDidMount(), didnt work!

I would suggest you to use a state in the Main component of your application (usually App.jsx) which will control loading. When you start the app the state will be true and only after checking all you need to check it will beacome false. If state is loading you will show a spinner or whatever you want and when it is not loading, the website:

class App extends Component {
    constructor(props) {
        super(props);
        this.state = { loading: true }
    }


    componentDidMount () {
       checkToken()
           .then(() => this.setState({ loading: false });

    }

    if (loading) {
        return <Spinner /> // or whatever you want to show if the app is loading
    }
    return (
        ...rest of you app
    )
}

If any doubt just let me know.

you can use Suspense and lazy:)

   import React, { Suspense } from 'react';
    
    const OtherComponent = React.lazy(() => import('./OtherComponent'));
    
    function MyComponent() {
      return (
        <div>
          <Suspense fallback={<div>loading...</div>}>
            <OtherComponent />
          </Suspense>
        </div>
      );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM