Javascript 如何从localstorage获取项目?

Javascript 如何从localstorage获取项目?,javascript,reactjs,typescript,local-storage,next.js,Javascript,Reactjs,Typescript,Local Storage,Next.js,我尝试使用next.js从本地存储中获取一个项目,而无需重新启动我的页面 我使用以下代码: 从“@material ui/core”导入{ThemeProvider}”; 从“react”导入{FC,useffect,useState}; 从“./hooks/ContextStore”导入{useStore}; 从“./theme/theme”导入{darkTheme,theme}; 从“/Navbar/Navbar”导入导航栏; 常量布局:FC=({children})=>{ const[d

我尝试使用next.js从本地存储中获取一个项目,而无需重新启动我的页面

我使用以下代码:

从“@material ui/core”导入{ThemeProvider}”;
从“react”导入{FC,useffect,useState};
从“./hooks/ContextStore”导入{useStore};
从“./theme/theme”导入{darkTheme,theme};
从“/Navbar/Navbar”导入导航栏;
常量布局:FC=({children})=>{
const[darkMode,setDarkMode]=useState(false);
const store=useStore();
useffect(()=>{
setDarkMode(JSON.parse(window.localStorage.getItem(“暗模式”));
},[store.darkMode]);
console.log(“did render”);
返回(
{儿童}
);
};

导出默认布局从外观上看,因为您的状态值总是来自localstorage,所以您不需要将其存储在状态中。 你可以这样做:

const isClient = typeof window !== undefined;
const Layout: FC = ({ children }) => {
  const store = useStore();
  const darkMode = isClient && JSON.parse(window.localStorage.getItem("dark-mode"));

  return (
    <ThemeProvider theme={darkMode ? darkTheme : theme}>
      <Navbar />
      {children}
    </ThemeProvider>
  );
}
export default Layout;

初始化状态时,如何从localstorage
const[darkMode,setDarkMode]=useState(JSON.parse(window.localstorage.getItem(“暗模式”))设置值我认为,您应该在本地存储值中查找更改(在useEffect的依赖项数组中),而不是状态,因为在更新本地存储值时,您正在查找本地存储值中的更改。我无法使用next.js访问useEffect/componentDidUpdate之外的本地存储。这个答案有帮助吗?我已经用类组件试过了。componentDidMount是无用的,因为它不会获得更新状态。使用componentDidUpdate,我得到了与useEffect相同的结果-它仍然会重新启动应用程序。谢谢,但因为我使用的是next.js,无法在useEffect\ComponentDidUpdate之外访问localstorage该窗口对象仅在客户端可用,您可以使用此
const isClient=typeof window!==未定义我已经用这个更新了答案谢谢你的评论,我已经试过了,但是没有用。我上传了一张图片。它仍然表示窗口对象未定义,如何将isClient转为函数或将其移动到组件中?返回相同的结果-窗口对象未定义。不管它是在函数组件内部还是外部。
const storageDarkMode = JSON.parse(window.localStorage.getItem("dark-mode"));
useEffect(() => {
  setState(storageDarkMode);
}, [storageDarkMode])