简体   繁体   English

如何在加载 dom 之前验证用户令牌?

[英]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.我想在加载 DOM 之前验证用户令牌(存储在本地存储中),因此用户将立即看到正确的 DOM。 window.onload and document.onreadystatechange triggers too late for that. window.onloaddocument.onreadystatechange触发太晚了。 (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.创建一个 state 变量 canShow 最初设置为 false,现在在 useEffect 回调 function 验证令牌并根据验证切换 canShow。 And in the return function render the dom only if canShow is true.并且在返回 function 仅当 canShow 为真时才渲染 dom。

PS You can do the same using class based component but react encourages developers to use functional components as much as possible. PS 你可以使用基于 class 的组件来做同样的事情,但 react 鼓励开发人员尽可能多地使用功能组件。

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 ).您可以尝试在 App.js (起始反应文件)中使用生命周期方法 - componentDidMount。 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.然后在你的渲染 function 中使用这个 state 来相应地更新你的 DOM。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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