」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Zustand 中的 createWithEqualityFn 測試案例進行了解釋。

Zustand 中的 createWithEqualityFn 測試案例進行了解釋。

發佈於2024-10-31
瀏覽:673

在本文中,我們將了解為驗證 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