最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React - correct way to wait for page load? - Stack Overflow

programmeradmin3浏览0评论

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!

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!

Share Improve this question asked May 4, 2020 at 16:20 js-learnerjs-learner 5072 gold badges11 silver badges28 bronze badges 2
  • Did you try listening for 'load' event? stackoverflow.com/a/43739277/3113485 – terrymorse Commented May 4, 2020 at 16:30
  • Can you show some of the code you have yet implemented? – deathstroke Commented May 4, 2020 at 16:35
Add a comment  | 

3 Answers 3

Reset to default 8

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>
      );
    }

Add this somewhere in the UI tree (maybe add it in the root component itself)

// will run once, after app has loaded

useEffect(() => {
  // your code here
}, []);
发布评论

评论列表(0)

  1. 暂无评论