我有这个 github 仓库:https://github.com/salmanfazal01/next-firebase-starter https://github.com/salmanfazal01/next-firebase-starter
基本上我正在使用 NextJS、Firebase 和 Zustand 创建一个基本样板作为全局状态管理器
我无法在 Zustand 中保留主题、用户等一些状态。刷新窗口后,它默认返回默认主题。
我确实尝试了 zustand 提供的持久中间件,尽管它有效,但它会导致服务器和客户端的内容不匹配错误
Error: Hydration failed because the initial UI does not match what was rendered on the server.
我将如何在不使用其他库(如下一个主题)的情况下将主题模式保留在状态中?
在 Next.js 13.4 中,您只需添加本文中提到的代码即可。我已链接到该文章:祖斯坦文章 https://docs.pmnd.rs/zustand/integrations/persisting-store-data#skiphydration
商店.ts:
"use client";
import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
export const useBearStore = create(
persist(
(set: any, get: any) => ({
bears: 0,
addABear: () => set({ bears: get().bears + 1 }),
}),
{
name: "food-storage", // name of the item in the storage (must be unique)
storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used
skipHydration: true,
}
)
);
页面.tsx:
"use client";
import { useBearStore } from "@/store";
import React, { useState, useEffect } from "react";
const page = () => {
//TODO: MUST BE ADD THIS CODE TO REMOVE HYDRATION ERROR::
useEffect(() => {
useBearStore.persist.rehydrate();
}, []);
function Controls() {
const increasePopulation = useBearStore((state: any) => state.addABear);
return (
<button
className="py-4 px-2 rounded-md bg-blue-400"
onClick={increasePopulation}
>
one up
</button>
);
}
const DisplayCounter = () => {
const counter = useBearStore((state: any) => state.bears);
return <div>Counter: {counter}</div>;
};
return (
<div>
<h1>Hello Do you see me</h1>
{Controls()}
{DisplayCounter()}
</div>
);
};
export default page;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)