【问题标题】:How to set object key in state using zustand如何使用 zustand 将对象键设置为状态
【发布时间】:2021-03-30 10:21:57
【问题描述】:

我正在使用 zustand 进行状态管理。我的商店设置如下:

import create from 'zustand';

export const useStore = create((set) => ({
    filters: {searchQuery: 'hello', evaluationMonth : null},
    setFilters: (e) => set((state) => ({filters : {evaluationMonth : 'New Month'}})),
}))

当我调用 setFilters 时,我只希望 evaluationMonth 发生变化,但它也会删除现有值(在本例中为 searchQuery)。如何在更改所需值的同时保留旧状态。

【问题讨论】:

  • 标题可能有点偏,zustand 中的“persist”是middleware,用于在重新加载或关闭网站后利用本地存储保持状态。一个更好的标题应该是“如何避免在改变它时丢失旧的对象状态”。

标签: reactjs zustand


【解决方案1】:

您可以通过在 set 函数中传播 state 参数来做到这一点。 确保您要覆盖的值是对象中的最后一个元素,以避免它被旧状态扩展覆盖。

export const useStore = create((set) => ({
    filters: {searchQuery: 'hello', evaluationMonth : null},
    setFilters: (e) => set((state) => ({filters : {...state.filters, evaluationMonth : 'New Month'}})),
}))

【讨论】:

    【解决方案2】:

    为避免分散每个级别的状态并保持代码与示例相似,您还可以使用 immer 作为中间件。如果您不熟悉不变性,这将为您节省大量调试时间。

    import create from 'zustand';
    import produce from 'immer';
    
    export const useStore = create((set) => ({
      filters: {searchQuery: 'hello', evaluationMonth : null},
      setFilters: () => set(produce(state => { state.filters.evaluationMonth = 'New Month' }))
    }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-06
      • 2019-12-27
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 2020-09-10
      相关资源
      最近更新 更多