{"id":1960,"date":"2025-10-02T01:27:37","date_gmt":"2025-10-01T17:27:37","guid":{"rendered":"https:\/\/womeifei.cn\/?p=1960"},"modified":"2025-10-02T15:24:18","modified_gmt":"2025-10-02T07:24:18","slug":"zustand-react%e7%8a%b6%e6%80%81%e7%ae%a1%e7%90%86%e5%b7%a5%e5%85%b7","status":"publish","type":"post","link":"https:\/\/womeifei.cn\/index.php\/2025\/10\/02\/zustand-react%e7%8a%b6%e6%80%81%e7%ae%a1%e7%90%86%e5%b7%a5%e5%85%b7\/","title":{"rendered":"Zustand &#8212; React\u72b6\u6001\u7ba1\u7406\u5de5\u5177"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">\u4e3b\u8981\u5185\u5bb9<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">\u57fa\u672c\u4f7f\u7528<\/h3>\n\n\n\n<h3 class=\"wp-block-heading\">\u5f02\u6b65\u548cimmer\u4e2d\u95f4\u4ef6<\/h3>\n\n\n\n<h3 class=\"wp-block-heading\">\u7b80\u5316\u72b6\u6001\u83b7\u53d6 useShallow<\/h3>\n\n\n\n<h3 class=\"wp-block-heading\">Redux DevTools \u67e5\u770b\u72b6\u6001<\/h3>\n\n\n\n<h3 class=\"wp-block-heading\">persist\u4e2d\u95f4\u4ef6\u8fdb\u884c\u6301\u4e45\u5316<\/h3>\n\n\n\n<h3 class=\"wp-block-heading\">\u4f7f\u7528subscribe\u8ba2\u9605<\/h3>\n\n\n\n<h3 class=\"wp-block-heading\">\u4f7f\u7528setState\u548cgetState\u89c4\u6574\u4ee3\u7801<\/h3>\n\n\n\n<h2 class=\"wp-block-heading\">\u4ee3\u7801\u793a\u4f8b<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>\/src\/store\/appleStore.ts<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import { create } from \"zustand\";\nimport { createJSONStorage, devtools, persist, subscribeWithSelector } from \"zustand\/middleware\";\nimport { immer } from \"zustand\/middleware\/immer\";\n\/\/immer\u4e2d\u95f4\u4ef6 \u7b80\u5316state\u64cd\u4f5c\n\/\/ subscribeWithSelector \n\ninterface AppleStateType {\n    price: number\n    count: number,\n    color: string,\n    \/\/ increment: () => void,\n    \/\/ decrement: () => void,\n    \/\/ getTotal: () => number,\n    \/\/ doubleCount: () => Promise&lt;undefined> \/\/async\u51fd\u6570\u8fd4\u56dePromise \u6ca1\u6709return \u4efb\u4f55\u503c \u76f8\u5f53\u4e8ereturn undefined\n}\n\/\/ \u5de5\u5177\u51fd\u6570 get() set()\nconst useAppleStore = create&lt;AppleStateType>()(immer(devtools(\n    subscribeWithSelector(\n        persist(() => ({\n            price: 7.0,\n            count: 10,\n            color: 'red',\n            \/\/partialize: (state) => ({ price: state.price }) \u53ea\u5bf9\u4ef7\u683c\u8fdb\u884c\u6301\u4e45\u5316\n\n            \/\/  partialize: (state) => Object.fromEntries(\n            \/\/     Object.entries(state).filter((&#91;key, _]) => !&#91;'price'].includes(key))\n            \/\/ )  \u9664\u4e86\u4ef7\u683c\u90fd\u6301\u4e45\u5316\n        }), {\n            name: 'myAppleStore',\n            partialize: (state) => Object.fromEntries(\n                Object.entries(state).filter((&#91;key, _]) => !&#91;'price'].includes(key))\n            ),\n            storage: createJSONStorage(() => sessionStorage) \/\/\u6307\u5b9a\u5b58\u50a8\u4f4d\u7f6e\n        })\n    ),\n    { enabled: true, name: \"Apple Store\" })))\n\nexport default useAppleStore\n\nexport const increment = () => {\n    useAppleStore.setState((state) => { state.count += 1 })\n}\n\n\nexport const decrement = () => {\n    useAppleStore.setState((state) => { state.count -= 1 })\n}\n\nexport const getTotal = () => {\n    return useAppleStore.getState().price * useAppleStore.getState().count\n}\n\nexport const doubleCount = async () => {\n    const rate = await Promise.resolve(2)\n\n    useAppleStore.setState((state) => { state.count *= rate })\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>\/src\/App.tsx<\/strong><\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import { shallow, useShallow } from \"zustand\/shallow\"\nimport useAppleStore, { decrement, doubleCount, getTotal, increment } from \".\/store\/appleStore\"\nimport { useEffect, useState } from \"react\"\n\nconst Child1 = () => {\n  const price = useAppleStore(state => state.price)\n  const count = useAppleStore(state => state.count)\n  \/\/\u4f7f\u7528setState\u4fee\u6539\u72b6\u6001\n  const myLocalAction = () => {\n    useAppleStore.setState((state) => { state.count += 3 })\n  }\n  \/\/\u4f7f\u7528getState\u83b7\u53d6\u72b6\u6001\n  return (\n    &lt;>\n      &lt;h1>\u5355\u4ef7:{price}&lt;\/h1>\n      &lt;h1>\u6570\u91cf:{count}&lt;\/h1>\n      &lt;h1>\u91d1\u989d:{getTotal()}&lt;\/h1>\n      &lt;button onClick={increment}> +1 &lt;\/button>\n      &lt;button onClick={decrement}> -1 &lt;\/button>\n      &lt;button onClick={doubleCount}> x2 &lt;\/button>\n      &lt;button onClick={myLocalAction}>\u7ec4\u4ef6\u4e00 \u72ec\u6709+3\u52a8\u4f5c &lt;\/button>\n\n      &lt;div>\u4f7f\u7528getState\u83b7\u53d6\u72b6\u6001: {useAppleStore.getState().count}&lt;\/div>\n    &lt;\/>\n  )\n}\n\nconst Child2 = () => {\n\n  \/\/\u89e3\u6784\u83b7\u53d6 \u9ed8\u8ba4\u83b7\u53d6\u6240\u6709\u72b6\u6001 \n  \/\/Child1\u4e2d\u72b6\u6001\u6539\u53d8 Child2\u4f9d\u65e7\u4f1a\u91cd\u65b0\u6e32\u67d3\n  \/\/ const { price, color } = userAppleStore()\n  const &#91;text, setText] = useState('\u592a\u5c11')\n\n\n  \/\/useShallow\n\n  \/\/useShallow\u7528\u4e8e\u4f18\u5316 zustand \u72b6\u6001\u9009\u62e9\uff0c\u907f\u514d\u4e0d\u5fc5\u8981\u7684\u6e32\u67d3\n  \/\/\u5b83\u4f1a\u5bf9\u65b0\u65e7\u72b6\u6001\u8fdb\u884c\u6d45\u6bd4\u8f83\uff0c\u53ea\u6709\u771f\u6b63\u53d8\u5316\u65f6\u624d\u89e6\u53d1\u66f4\u65b0\n  const { price, color } = useAppleStore(useShallow(state => ({\n    price: state.price,\n    color: state.color,\n  })))\n\n  \/\/\u5e0c\u671b\u53ea\u8ba2\u9605\u4e00\u6b21\n  \/\/\u72b6\u6001\u6539\u53d8\u4e4b\u540e \u6267\u884c\u4e86\u8ba2\u9605\u7684\u4ee3\u7801\n  useEffect(() => {\n    const cancelSub = useAppleStore.subscribe(\n      state => state.count, \/\/\u76d1\u542c\u6307\u5b9a\u7684\u72b6\u6001\n      (count, preCount) => {\n        if (count > 7 &amp;&amp; preCount &lt;= 7 || count === preCount &amp;&amp; count > 7) {\n          setText('\u5df2\u7ecf\u5f88\u591a\u4e86')\n        } else if (count &lt;= 7 &amp;&amp; preCount > 7 || count === preCount &amp;&amp; count &lt;= 7) {\n          setText('\u592a\u5c11')\n        }\n      },\n      {\n        equalityFn: shallow,\n        fireImmediately: true\n      },\n\n    )\n    return cancelSub\n  }, &#91;])\n\n\n  console.log('---Child2---')\n  return (\n    &lt;>\n      &lt;h1>\u5355\u4ef7:{price}&lt;\/h1>\n      &lt;h1>\u989c\u8272:{color}&lt;\/h1>\n      &lt;h1>{text}&lt;\/h1>\n      {\/* \u4f8b\u5982count\u4e3a0\u65f6 \u6bcf\u52a0\u4e00\u6b21 Child2\u90fd\u4f1a\u91cd\u65b0\u6e32\u67d3 \u6211\u60f3\u8981\u4ed6\u6539\u53d8\u5230>7\u518d\u91cd\u65b0\u6e32\u67d3  *\/}\n      {\/* \u4f7f\u7528\u8ba2\u9605 *\/}\n    &lt;\/>\n  )\n}\nfunction App() {\n\n  return (\n    &lt;>\n      &lt;Child1>\n\n      &lt;\/Child1>\n      &lt;hr \/>\n      &lt;Child2>\n\n      &lt;\/Child2>\n    &lt;\/>)\n}\n\nexport default App\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u4e3b\u8981\u5185\u5bb9 \u57fa\u672c\u4f7f\u7528 \u5f02\u6b65\u548cimmer\u4e2d\u95f4\u4ef6 \u7b80\u5316\u72b6\u6001\u83b7\u53d6 useShallow Redux DevTools  [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[47,1],"tags":[],"class_list":["post-1960","post","type-post","status-publish","format-standard","hentry","category-react","category-1"],"_links":{"self":[{"href":"https:\/\/womeifei.cn\/index.php\/wp-json\/wp\/v2\/posts\/1960","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/womeifei.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/womeifei.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/womeifei.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/womeifei.cn\/index.php\/wp-json\/wp\/v2\/comments?post=1960"}],"version-history":[{"count":5,"href":"https:\/\/womeifei.cn\/index.php\/wp-json\/wp\/v2\/posts\/1960\/revisions"}],"predecessor-version":[{"id":1968,"href":"https:\/\/womeifei.cn\/index.php\/wp-json\/wp\/v2\/posts\/1960\/revisions\/1968"}],"wp:attachment":[{"href":"https:\/\/womeifei.cn\/index.php\/wp-json\/wp\/v2\/media?parent=1960"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/womeifei.cn\/index.php\/wp-json\/wp\/v2\/categories?post=1960"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/womeifei.cn\/index.php\/wp-json\/wp\/v2\/tags?post=1960"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}