简体   繁体   English

如何在 React 应用程序中的 ReactDOM.render 之前初始化 LocalStorage 中的数据

[英]How to initialize the data from LocalStorage before ReactDOM.render in a react App

I am using redux as my state management system and storing my authentication token in LocalStorage.我使用 redux 作为我的 state 管理系统并将我的身份验证令牌存储在 LocalStorage 中。 Whenever I am logged in and reload my page it flickers between logged out state and then gets back to the logged-in page.每当我登录并重新加载我的页面时,它都会在注销 state 之间闪烁,然后返回登录页面。 How can I initialize data from LocalStorage and the do the rendering after data has come?如何从 LocalStorage 初始化数据并在数据到来后进行渲染?

one approach is store in localStorage and then grab straight from state initialisation when your component loads.一种方法是存储在 localStorage 中,然后在加载组件时直接从 state 初始化中获取。 consider your top level component state, you could do something like this:考虑您的顶级组件 state,您可以执行以下操作:

const [user, setUser] = useState(JSON.parse(localStorage.getItem('user')))

this is how I overcame the flicker in my app.这就是我克服应用程序闪烁的方法。 if you grab it immediately rather than in useEffect or when the component mounts, it should work如果您立即抓住它而不是在useEffect或组件安装时,它应该可以工作

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

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