UNPKG

mt-flowbite-react

Version:

Official React components built for Flowbite and Tailwind CSS

85 lines (84 loc) 2.92 kB
'use client'; import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { createContext, useRef, useContext } from "react"; import { create, useStore } from 'zustand'; import { persist, subscribeWithSelector } from "zustand/middleware"; export const createRenderlice = (set, get, store) => { //注意: store 这个参数,还没弄清楚是什么意思。 // console.log("initState123:", store) return ({ title: "title1", setTitle(title) { set({ ...get(), title }); }, addItem(item) { // get(). }, ...store, }); }; export const createNodeStore = (initProps) => { return create()(persist(subscribeWithSelector((...a) => ({ ...createRenderlice(...a), ...initProps, })), { name: `demo3-${initProps?.id}`, version: 1, skipHydration: true, onRehydrateStorage(state) { }, migrate(persistedState, version) { console.log("version", version, persistedState); return persistedState; }, })); }; //------------------------------------------------------------------------------------------- // 一般情况下 的Context 及其 hook const Context = createContext(null); export function Demo3Provider({ children, ...props }) { const storeRef = useRef(); if (!storeRef.current) { console.log("create store:", props.id); storeRef.current = createNodeStore(props); } return (_jsxs(Context.Provider, { value: storeRef.current, children: [children, _jsx(SubscriptionSetup, {})] })); } function SubscriptionSetup() { const store = useDemo3Store(); return (_jsx("div", { className: "bg-blue-500" })); } export function useDemo3Store(selector, equals) { const store = useContext(Context); if (!store) throw new Error('Missing Demo3Provider'); if (selector) { return useStore(store, selector, equals); } else { return store; } } //------------------------------------------------------------------------------------------------------------------------ // 额外的全局的 上下文及其钩子 const ContextGlobal = createContext(null); export function Demo3GlobalProvider({ children, ...props }) { const storeRef = useRef(); if (!storeRef.current) { console.log("create store:", props.id); storeRef.current = createNodeStore(props); console.log("create store current:", storeRef.current); } return (_jsx(ContextGlobal.Provider, { value: storeRef.current, children: children })); } export function useDemo3GlobalStore(selector, equals) { const store = useContext(ContextGlobal); console.log("global store", store); if (!store) throw new Error('Missing Demo3GlobalProvider'); if (selector) { return useStore(store, selector, equals); } else { return store; } }