如何从 v4 迁移到 v5
我们强烈建议在迁移到 v5 之前更新到 v4 的最新版本。它会显示所有弃用警告,而不会破坏您的应用程序。
v5 的变化
- 删除默认导出
- 删除弃用功能
- 将 React 18 设为最低要求版本
- 将 use-sync-external-store 设为对等依赖项(在
zustand/traditional
中用于createWithEqualityFn
和useStoreWithEqualityFn
) - 将 TypeScript 4.5 设为最低要求版本
- 删除 UMD/SystemJS 支持
- 在 package.json 中组织入口点
- 删除 ES5 支持
- 当 setState 的 replace 标志设置时,更严格的类型
- 持久化中间件行为变化
- 其他小改进(技术上是重大变化)
迁移指南
使用自定义相等函数如 shallow
v5 中的 create
函数不支持自定义相等函数。
如果您使用自定义相等函 数如 shallow
,最简单的迁移方法是使用 createWithEqualityFn
。
// v4
import { create } from 'zustand'
import { shallow } from 'zustand/shallow'
const useCountStore = create((set) => ({
count: 0,
text: 'hello',
// ...existing code...
}))
const Component = () => {
const { count, text } = useCountStore(
(state) => ({
count: state.count,
text: state.text,
}),
shallow,
)
// ...existing code...
}
这可以在 v5 中使用 createWithEqualityFn
完成:
npm install use-sync-external-store
// v5
import { createWithEqualityFn as create } from 'zustand/traditional'
// 其余部分与 v4 相同
或者,对于 shallow
用例,您可以使用 useShallow
钩子:
// v5
import { create } from 'zustand'
import { useShallow } from 'zustand/shallow'
const useCountStore = create((set) => ({
count: 0,
text: 'hello',
// ...existing code...
}))
const Component = () => {
const { count, text } = useCountStore(
useShallow((state) => ({
count: state.count,
text: state.text,
})),
)
// ...existing code...
}
需要稳定的选择器输出
v5 中有一个行为变化,以匹配 React 的默认行为。如果选择器返回一个新引用,它可能会导致无限循环。
例如,这可能会导致无限循环。
// v4
const [searchValue, setSearchValue] = useStore((state) => [
state.searchValue,
state.setSearchValue,
])