Next.JS - Access `localStorage` before rendering page

自闭症网瘾萝莉.ら 提交于 2020-06-23 04:16:38

问题


Let's say I have a user's account information stored in localStorage (client side). I need my Next.JS app to render the webpage's navbar based on what's stored in localStorage (login or logout button). How can I first obtain the value from the client and then render the page? Or perhaps that isn't even what Next.JS is meant to do?


回答1:


You can do something like this:

  1. Use a variable in the state to prevent the page from being rendered
  2. Use componentDidMount to load data from localStorage
  3. When data is loaded, setState to allow component to be rendered.

It's a react issue, not a next.js issue. You could use Conditional rendering for step 1. Also read up on state here, and lastly componentDidMount.



来源:https://stackoverflow.com/questions/54819721/next-js-access-localstorage-before-rendering-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!