简体   繁体   中英

How to verify user token before the dom is loaded?

I want to verify the user token (that stored in local storage) before the DOM is loaded, so the user will see immediately the correct DOM. window.onload and document.onreadystatechange triggers too late for that. (this is a react app)

what is the appropriate event?

thanks!

Create a state variable canShow initially set to false, now in the useEffect callback function verify the token and according to the verification toggle canShow. And in the return function render the dom only if canShow is true.

PS You can do the same using class based component but react encourages developers to use functional components as much as possible.

You could add a script tag in the head

<head>
  <!-- meta, css, ... -->

  <script>
    //This gets executed before
  </script>
</head>

<body>
  The body gets parsed
</body>

You can try using the lifecycle method - componentDidMount in your App.js ( the starting react file ). Put your logic in this lifecycle method. For example -

async componentDidMount() {
    await this.setState({
      user:localStorage.getItem("user")
    })
}

And then use this state in your render function to update your DOM accordingly.

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