Next.JS-在渲染页面之前访问`localStorage` [英] Next.JS - Access `localStorage` before rendering page

查看:1032
本文介绍了Next.JS-在渲染页面之前访问`localStorage`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在localStorage(客户端)中存储了一个用户的帐户信息.我需要Next.JS应用程序基于localStorage中存储的内容(登录或注销按钮)来呈现网页的导航栏.如何首先从客户端获取值,然后然后呈现页面?也许这甚至不是Next.JS的本意?

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. 在状态下使用变量以防止呈现页面
  2. 使用componentDidMountlocalStorage加载数据
  3. 加载数据时,请设置setState以允许呈现组件.
  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.

这是一个反应性问题,而不是next.js问题. 您可以将条件渲染用于步骤1. 另外,在此处阅读状态,最后

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.

这篇关于Next.JS-在渲染页面之前访问`localStorage`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆