xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Immer & immutable state All In One

Immer & immutable state All In One

Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.

Immer(德语:always)是一个小包,可让您以更方便的方式处理不可变状态。

image

https://immerjs.github.io/immer/

https://github.com/immerjs/immer

image

$ npm install immer

Immer 如何工作

基本思想是,使用 Immer,您会将所有更改应用到临时 draft,它是 currentState 的代理
一旦你完成了所有的 mutations,Immer 将根据对 draft state 的 mutations 生成 nextState。
这意味着您可以通过简单地修改数据来与数据交互,同时保留不可变数据的所有好处。

image

https://immerjs.github.io/immer/zh-CN/#immer-如何工作

demos

import produce from 'immer'

const todos = [
  {
    text: 'learn immer',
    done: false
  },
  {
    text: 'simplify all code',
    done: false
  }
]

const nextTodos = produce(todos, draft => {
  draft.push({ text: 'get coffee', done: true })
  draft[0].done = true
})

console.log(nextTodos.length)
console.log(todos[0].done)
console.log(nextTodos[0].done)

console.log(nextTodos === todos)
console.log(nextTodos[0] === todos[0])
console.log(nextTodos[1] === todos[1])

// Uncomment this line to raise the read-only exception
// nextTodos[0].done = false

image

https://egghead.io/lessons/redux-simplify-creating-immutable-data-trees-with-immer

https://egghead.io/lessons/javascript-introduction-to-the-in-depth-immer-course

https://immerjs.github.io/immer/zh-CN/example-setstate/

React Hooks

Use immer to drive state with a React hooks

https://github.com/immerjs/use-immer

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-04-25 16:14  xgqfrms  阅读(7)  评论(0编辑  收藏  举报