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

使用React与Zustand合并双Store,仅为createSelectionStore集成Zundo遇报错

解决Zustand合并Store并集成Zundo的报错问题

错误原因

你当前的写法是直接通过create()生成了createSelectionStore和createBikePathStore,它们已经是完整的Store钩子,并非可接收set参数的状态创建器,因此无法通过传入set来合并状态。

正确实现方式

需要将两个Store定义为纯创建器函数(不直接调用create),再给需要集成Zundo的createSelectionStore套上temporal中间件,最后合并创建:

import { create } from 'zustand'
import { temporal } from 'zundo'

// 定义纯状态创建器,不调用create
const createSelectionStore = (set) => ({
    selected: [], // 选中的路径索引
    select: (index) => set(state => ({
        selected: [...state.selected, index]
    })),
    deselect: () => set({ selected: [] })
})

// 定义另一个纯状态创建器
const createBikePathStore = (set) => ({
    paths: [],
    visible: false,
    setPaths: (paths) => set({ paths }),
    setVisible: (visible) => set({ visible })
})

// 合并两个创建器,给selection store套上temporal中间件
const useBikePathStore = create((set, get) => ({
    ...temporal(createSelectionStore)(set, get),
    ...createBikePathStore(set, get)
}))

export default useBikePathStore

关键说明

  • 将Store改为纯函数后,它们可以接收set和get参数,适配Zustand的合并逻辑
  • temporal中间件需要包裹在createSelectionStore外层,再传入set和get,这样只有选择状态会被纳入撤销/重做体系
  • 合并时需要同时传入set和get参数,确保中间件和状态方法能正常工作

内容的提问来源于stack exchange,提问作者Florian G

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:55:38