You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Zustand设置切片黑名单,阻止指定切片持久化

实现Zustand状态持久化的黑名单(排除指定切片)

Zustand的persist中间件可以通过partialize配置项实现类似Redux-Persist黑名单的功能,用来过滤掉不需要持久化的状态切片。针对你的需求,只需要在persist的配置中添加这个函数,排除business相关的状态即可。

修改后的完整代码如下:

import { create } from 'zustand';
import { createAuthSlice } from './createAuthSlice';
import { createUserSlice } from './createUserSlice';
import { createBusinessSlice } from './createBusinessSlice';
import { persist, devtools } from 'zustand/middleware';
import { AuthState, BusinessState, UserState } from '../types/zustand';

interface RootState extends AuthState, UserState, BusinessState { }

export const useAppStore = create<RootState>()(
  devtools(
    persist(
      (set) => ({
        ...createAuthSlice(set),
        ...createUserSlice(set),
        ...createBusinessSlice(set),
      }),
      { 
        name: 'app-store',
        // 过滤掉不需要持久化的business切片状态
        partialize: (state) => {
          const { business, ...persistedState } = state;
          return persistedState;
        }
      },
    )),
)

关键说明:

  • partialize函数接收当前的完整状态state,返回需要被持久化的状态部分。
  • 这里通过对象解构,把business相关的属性从状态中剥离,只保留auth和user切片的状态进行持久化。
  • 如果你的business切片是分散的多个属性(而非单个business对象),可以直接列出这些属性进行排除,比如:
    partialize: (state) => {
      const { businessName, businessId, ...persistedState } = state;
      return persistedState;
    }
    

内容的提问来源于stack exchange,提问作者Soheil Bakhtyari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 13:58:52