使用 Immer 实现在 Zustand 中更新深层对象

在开发 React 应用程序时,状态管理是一个关键问题,而 Zustand 是一个简单且强大的状态管理库,可以与 React 结合使用。在使用 Zustand 时,有时需要更新深层对象中的属性,这可能需要繁琐的手动对象复制。但是,使用 Immer 库可以简化这一过程。

首先,让我们看一下在不使用 Immer 的情况下,如何在 Zustand 中更新深层对象的属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import create from 'zustand';

// 定义一个状态对象
const useStoreWithoutImmer = create(set => ({
user: {
name: 'Alice',
age: 30,
address: {
city: 'New York',
country: 'USA'
}
},
updateCity: newCity => set(state => ({ user: { ...state.user, address: { ...state.user.address, city: newCity } } }))
}));

export default useStoreWithoutImmer;

在上面的示例中,我们使用了展开运算符 (spread operator) 来手动创建新的对象,以更新深层对象中的属性。这种方法可能会变得繁琐,尤其是当对象结构变得更加复杂时。

现在,让我们看看如何使用 Immer 简化这一过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import create from 'zustand';
import produce from 'immer';

// 定义一个状态对象
const useStoreWithImmer = create(set => ({
user: {
name: 'Alice',
age: 30,
address: {
city: 'New York',
country: 'USA'
}
},
updateCity: newCity => set(produce(state => {
state.user.address.city = newCity;
}))
}));

export default useStoreWithImmer;

在上面的示例中,使用了 Immer 提供的 produce 函数,这样就可以直接修改状态对象中的属性,而不必手动创建新对象。

通过以上两个示例的对比,可以清楚地看到使用 Immer 可以大大简化在 Zustand 中更新深层对象属性的过程,减少了手动对象复制的繁琐工作。

在实际项目中,选择使用 Immer 可以让代码更加简洁和易于维护,尤其是当涉及到复杂的对象结构和深层对象属性时。

希望本文能帮助你更好地理解如何使用 Immer 配合 Zustand 来更新深层对象属性,以及比较不使用 Immer 的版本。