Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

基于zustand维护的一套跨框架(react/vue)跨应用的状态管理及共享方案 #90

Open
AwesomeDevin opened this issue Jun 20, 2023 · 0 comments

Comments

@AwesomeDevin
Copy link
Owner

zustand-pub

只要从事前端开发,不论是小程序还是web,都绕不开状态管理。
众所周知, zustand 是一套轻量、便捷、可拓展的状态管理方案,不论国内 or 国外,都备受喜爱,star 数已接近 3W。

zustand-pub 则基于zustand为 Iframe、微前端、Module Fedetation、模块化、组件化 等业务场景,提供 跨应用、跨框架 的 状态管理 及 状态共享 能力。

为什么你需要 zustand-pub

  1. 应用/组件 间可以 相互调用/修改 state,并 触发组件渲染, 如果你是iframe,则可以抛弃掉难维护的postMessage + addeventlistener + action了,如果你是微前端,也不在需要eventCenter + action了,直接调用 action 修改 state 即可。
  2. 应用/组件 间 状态可以被缓存,包括 iframe、微前端等。
  3. 平时我们在业务组件引用全局 store 时会导致夸应用无法复用的问题,降低了组件的可复用性,而基于zustand-pub则不会再存在此类问题,复用性与开发效率并存。
  4. 基于 devtools 可以 同时调试/追踪多个应用间的 store,能够极大地降低应用间通信时的调试难度。
  5. 如果你正在使用 zustand 或 zustand-vue,那么使用 zustand-pub 将很简单。

哪些项目里可以使用?

使用案例

  1. 不同应用间基于修改目标应用的状态更新视图,也可以跨应用获取状态。不再需要维护postmessage或事件中心。
  • iframe
  • 微前端
    zustand-pub-micro-app.gif
  1. 在 npm\umd\module federation 组件库中直接使用应用状态
    业务组件库中,我们对于应用全局状态的引用还是比较频繁的,如是否登陆/用户信息等。这些信息如果基于组件props进行传参,在组件层级比较深的情况下,需要一层一层往下传,并且如果字段有增加或删除,也需要修改多层组件,

所以最理想的方案是直接从 store 中获取

import create from "zustand";

const useUserInfo = create<IState & IAction>((set) => ({
  userInfo: { name: '' },
  setUserInfoName(val: string) {
    set({
      userInfo: {
        name: val
      }
    })
  }
}))

const name = useUserInfo((state) => state.userInfo.name);

但此方案 useUserInfo 往往是跟着应用走的,在组件库中我们是无法使用的。

为此,可以引用zustand-pubuseUserInfo进行小小的改动:

import PubStore from 'zustand-pub'

import create from "zustand";

const pubStore = new PubStore('appKey')


const userInfoStore = pubStore.defineStore<<IState & IAction>>('userInfo',(set) => ({
  userInfo: { name: '' },
  setUserInfoName(val: string) {
    set({
      userInfo: {
        name: val
      }
    })
  }
}))

const useUserInfo = create(userInfoStore)
const name = useUserInfo((state) => state.userInfo.name);

npm\umd\module federation组件库下使用

import PubStore from "zustand-pub";
const pubStore = new PubStore('appKey')
const store = pubStore.getStore<IState & IAction>("userInfo");
const useUserInfo = create(userInfoStore)
const name = useUserInfo((state) => state.userInfo.name)

这里以react举例,如果你的应用是vue,也可以基于zustand-vue进行使用。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant