”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > Zustand 中的 createWithEqualityFn 测试用例进行了解释。

Zustand 中的 createWithEqualityFn 测试用例进行了解释。

发布于2024-10-31
浏览:512

在本文中,我们将了解为验证 createWithEqualityFn 而编写的测试用例,该测试用例可根据您可以传递的条件和相等函数来防止重新渲染。

以下代码摘自basic.test.ts

it('uses the store with a selector and equality checker', async () => {
  const useBoundStore = createWithEqualityFn(
    () => ({ item: { value: 0 } }),
    Object.is,
  )
  const { setState } = useBoundStore
  let renderCount = 0

  function Component() {
    // Prevent re-render if new value === 1.
    const item = useBoundStore(
      (s) => s.item,
      (_, newItem) => newItem.value === 1,
    )
    return (
      
renderCount: { renderCount}, value: {item.value}
) } const { findByText } = render( >, ) await findByText('renderCount: 1, value: 0') // This will not cause a re-render. act(() => setState({ item: { value: 1 } })) await findByText('renderCount: 1, value: 0') // This will cause a re-render. act(() => setState({ item: { value: 2 } })) await findByText('renderCount: 2, value: 2') })

Zustand 使用 Vitest 来满足其测试需求。让我们看一下上面的代码片段。

初始化createWithEqualityFn

const useBoundStore = createWithEqualityFn(
    () => ({ item: { value: 0 } }),
    Object.is,
  )

createWithEqualityFn 使用 state () => ({ item: { value: 0 } }) 进行初始化,相等函数为 Object.is

createWithEqualityFn test case in Zustand explained.

createWithEqualityFn 接受两个变量,createState 和 defaultEqualityFn。

防止重新渲染

// Prevent re-render if new value === 1.
    const item = useBoundStore(
      (s) => s.item,
      (_, newItem) => newItem.value === 1,
    )

useBoundStore 接受选择器和相等函数,用于根据匹配值防止重新渲染。

上面basic.test中的例子是用来防止值为1时重新渲染的。

await findByText('renderCount: 1, value: 0')

// This will not cause a re-render.
act(() => setState({ item: { value: 1 } }))
await findByText('renderCount: 1, value: 0')

// This will cause a re-render.
act(() => setState({ item: { value: 2 } }))
await findByText('renderCount: 2, value: 2')

这些断言验证状态更新不会导致任何重新渲染。

关于我们:

在 Think Throo,我们的使命是教授受开源项目启发的最佳实践。

通过在 Next.js/React 中练习高级架构概念,提高您的编码技能,学习最佳实践并构建生产级项目。

我们是开源的 — https://github.com/thinkthroo/thinkthroo (请给我们一颗星!)

通过我们基于代码库架构的高级课程来提高您的团队技能。请通过 [email protected] 联系我们以了解更多信息!

参考:

  1. https://github.com/pmndrs/zustand/blob/main/tests/basic.test.tsx#L92

  2. https://vitest.dev/guide/

版本声明 本文转载于:https://dev.to/thinkthroo/createwithequalityfn-test-case-in-zustand-explained-3lhl?1如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3