DEV Community

mikebui
mikebui

Posted on

Giới thiệu về Immer - Phần 2

Bài dịch từ trang chủ của Immer:
https://immerjs.github.io/immer/

Sử dụng produce

Immer sử dụng một chức năng mặc định thực hiện tất cả công việc.

produce(baseState, recipe: (draftState) => void): nextState

produce có baseState và một công thức (recipe) có thể được sử dụng để thực hiện tất cả các thay đổi trên bản nháp được chuyển vào. Điều thú vị về Immer là baseState sẽ không bị ảnh hưởng, nhưng nextState sẽ phản ánh tất cả các thay đổi được thực hiện đối với draftState .

Bên trong công thức (recipe), tất cả các API JavaScript tiêu chuẩn có thể được sử dụng trên đối tượng nháp, bao gồm các phép gán trường, thao tác xóa và thay đổi mảng, các thao tác Map và Set như push, pop, splice, set, sort, remove, v.v.

Bất kỳ sự thay đổi nào trong số đó không nhất thiết phải xảy ra ở gốc, nhưng nó được phép sửa đổi bất kỳ thứ gì ở bất kỳ đâu sâu bên trong bản nháp: draft.todos[0].tags["urgent"].author.age = 56

Lưu ý rằng bản thân hàm recipe thường không trả về bất kỳ thứ gì. Tuy nhiên, có thể trả về trong trường hợp bạn muốn thay thế toàn bộ đối tượng nháp bằng một đối tượng khác, để biết thêm chi tiết, hãy xem trả về dữ liệu mới.

import produce from "immer"

const baseState = [
    {
        title: "Learn TypeScript",
        done: true
    },
    {
        title: "Try Immer",
        done: false
    }
]

const nextState = produce(baseState, draftState => {
    draftState.push({title: "Tweet about it"})
    draftState[1].done = true
})
Enter fullscreen mode Exit fullscreen mode
// the new item is only added to the next state,
// base state is unmodified
expect(baseState.length).toBe(2)
expect(nextState.length).toBe(3)

// same for the changed 'done' prop
expect(baseState[1].done).toBe(false)
expect(nextState[1].done).toBe(true)

// unchanged data is structurally shared
expect(nextState[0]).toBe(baseState[0])
// ...but changed data isn't.
expect(nextState[1]).not.toBe(baseState[1])
Enter fullscreen mode Exit fullscreen mode

Thuật ngữ

  • (base)state, the immutable state passed to produce
  • recipe: the second argument of produce, that captures how the base state should be "mutated".
  • draft: the first argument of any recipe, which is a proxy to the original base state that can be safely mutated.
  • producer. A function that uses produce and is generally of the form (baseState, ...arguments) => resultState

Latest comments (0)