Stories

Detail Return Return

基於zustand維護的一套跨框架(react/vue)跨應用的狀態管理及共享方案 - Stories Detail

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. 以往模塊化管理的 store,在不同倉庫(應用)下複用時,狀態無法同步更新,而基於zustand-pub模塊管管理的 store,狀態將能夠同步更新,提升了研發過程中 store 邏輯複用的可行性及研發效率。
  5. 某些 iframe / 微前端 場景因為接口請求過多導致頁面渲染慢的,可以基於該方案進行子應用狀態預請求,優化用户體驗
  6. 基於 devtools 可以 同時調試/追蹤多個應用間的 store,能夠極大地降低應用間通信時的調試難度。
  7. 如果你正在使用 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進行使用。

Add a new Comments

Some HTML is okay.