如何使用 zustand 在状态中设置对象键

How to set object key in state using zustand

我正在使用 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)。我如何在更改所需值的同时保留旧状态。

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

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

为了避免分散每个级别的状态并使您的代码与您的示例相似,您还可以使用 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' }))
}));