NextJS 发出读取本地存储中已有项目的问题

NextJS issue reading items already in local storage

登录我的 NextJS 应用程序时,我将一些用户数据保存到本地存储。

我正在尝试将其呈现为始终显示用户名的小组件。我遇到的问题是它只是有时显示,其他时候显示为 null ... 似乎当我登录时,它显示为空,但当我重新加载页面时它工作。

这是我的;

import { useEffect } from 'react';

export default function ProfileDisplay() {
    useEffect(async () => {
        const userName = JSON.parse(localStorage.getItem('profile'));
        console.log(userName);
    }, []);

    return (
        <div>
            {userName}
        </div>
    )
}

它最初可能是空的,因为在您的服务器端没有“localStorage”对象。并且由于您使用空的 useEffect 调用 dependency array ,因此当用户名更改时它不会触发。所以你应该在 useEffect 之外声明 username 并将其放在 dependency array 中以监听变化。

export default function ProfileDisplay() {
  const userName = JSON.parse(localStorage.getItem('profile')); // moved it outside the useEffect 
  useEffect(() => {
    if(userName)
      console.log(userName); // do stuff with username
    
}, [userName]); // it will fire when username changes

return (
    <div>
        {userName}
    </div>
)
}

您可以将 userName 变量置于状态中,并在从 localStorage.

检索到其值后在您的 useEffect 中更新它
import { useEffect, useState } from 'react';

export default function ProfileDisplay() {
    const [userName, setUserName] = useState('')

    useEffect(() => {
        const profile = JSON.parse(localStorage.getItem('profile'));
        setUserName(profile);
    }, []);

    return (
        <div>{userName}</div>
    )
}