怎么实现边侧栏不变

    科技2022-07-12  135

    怎么实现边侧栏不变

    Immer is a light-weight javascript package used for working with immutable state in a very convenient way. Use of immer simplifies deep updates in the state of app components.

    Immer是一个轻量级的javascript软件包,用于以非常方便的方式处理不可变状态。 使用immer简化了应用程序组件状态的深层更新。

    For any medium-sized-application, there will always be a state (in fact, a lot of state). On top of that, there will be asynchronous actions that will keep updating the state. Predicting the state and tracking mutations which cause side-effects becomes a tedious job. So keeping the state immutable can help us in terms of performance, predictability and better mutation tracking. We can always predict the state at any given time.

    对于任何中型应用程序,总会有一个状态(实际上是很多状态)。 最重要的是,将有异步动作将不断更新状态。 预测状态并跟踪引起副作用的突变变得繁琐。 因此,保持状态不变是可以在性能,可预测性和更好的突变跟踪方面帮助我们的。 我们始终可以在任何给定时间预测状态。

    While the methods of using Object.assign() or spread operator are used for data mutation by creating new object copies and then mutating their values, the process becomes really complex when nested data (especially for arrays and objects) comes into picture (which can be easily seen in large projects).

    虽然使用Object.assign()或散布运算符的方法通过创建新的对象副本然后对其值进行突变来进行数据突变,但是当嵌套数据(尤其是数组和对象)出现在图片中时,过程变得非常复杂(可以在大型项目中很容易看到)。

    A few libraries like Immutable.js achieve the same, but it requires us to study a whole new API to be able to use them.

    一些类似Immutable.js的库可以实现相同的功能,但是它要求我们研究一种全新的API才能使用它们。

    This is where Immer comes to rescue as it achieves immutability in a much more streamlined manner. It removes all the overhead of verbose syntax and leads to clean and concise code. The code for using immer is inline with the standard javascript so it is easy to understand.

    这是Immer抢救的地方,因为它以更加简化的方式实现了不变性。 它消除了冗长语法的所有开销,并导致代码简洁明了。 使用immer的代码与标准javascript内联,因此很容易理解。

    Usage:

    用法 :

    To add immer:

    要添加沉浸式:

    yarn add immer

    A simple example of immer usage is::

    沉浸式用法的一个简单示例是:

    import produce from “immer”;const nextState = produce(baseState, draftState => { draftState.name = “John” draftState.age = 22})

    Here, the baseState is the current state of our app. A temporary copy of the current state is created which is the draftState. DraftState acts as a proxy of current state. All new changes are applied to this proxy state first and once all data mutation is done, we get our nextState. Thus enabling immutability of state in a much easier way.

    在这里,baseState是我们应用程序的当前状态。 创建当前状态的临时副本即draftState。 DraftState充当当前状态的代理。 所有新更改都将首先应用于此代理状态,一旦完成所有数据突变,我们便获得了nextState。 因此,以更容易的方式实现状态的不变性。

    How Immer works behind the scene:

    Immer在幕后的工作方式:

    Immer creates a temporary shadow tree which can be modified using the standard JavaScript APIs. The shadow tree is used to generate the next immutable state tree. This shadow tree is maintained using Proxies. Proxies are an exotic javascript feature that is nowadays available in all modern browsers.

    Immer创建了一个临时的影子树,可以使用标准JavaScript API对其进行修改。 影子树用于生成下一个不可变状态树。 该阴影树是使用代理维护的。 代理是一种奇特的javascript功能,如今在所有现代浏览器中都可用。

    const proxy = new Proxy(target, traps)

    The target is the original object which you want to proxy. The traps are objects that define which operations will be intercepted and how to redefine intercepted operations.

    目标是您要代理的原始对象。 陷阱是定义将拦截哪些操作以及如何重新定义拦截的操作的对象。

    Initially when the producer starts, a proxy is created, which is the draft object we pass to our function. Now as we traverse through the tree and try to modify something, it will immediately create a shallow clone of the target node and mark it as “modified”. This process is called “copy-on-write”. After all modifications are done we get a proxy tree which acts as a shadow of our base tree. Upon completion, the producer combines the clones and freezes the modified objects. This is how immutability is achieved using Immer.

    最初,当生产者启动时,将创建一个代理,这是我们传递给函数的草稿对象。 现在,当我们遍历树并尝试修改某些内容时,它将立即创建目标节点的浅表克隆并将其标记为“已修改”。 此过程称为“写时复制”。 完成所有修改后,我们将获得一个代理树,该代理树充当基础树的影子。 完成后,生产者将合并克隆并冻结修改的对象。 这就是使用Immer实现不变性的方式。

    Immer can be used wherever deep data mutation is required . For example, setState() function in React or Reducers in Redux.

    Immer可用于需要深度数据突变的任何地方。 例如,React中的setState()函数或Redux中的Reducers函数。

    this.setState(prevState => ({ items: { ...prevState.items, count: prevState.items.count + 1 } }))

    But by using produce from immer, it simple becomes :

    但是通过使用浸泡器产生的农产品 ,它变得简单起来:

    this.setState( produce(draft => { draft.items.count += 1 }))

    Let us try to understand immer in reducers with example.

    让我们尝试通过示例来了解沉浸在减速器中。

    Reducer using Object.assign or spread operator

    使用Object.assign或spread运算符的reducer

    Let us see an example of how immer makes the code simpler.

    让我们来看一个沉浸式如何使代码更简单的示例。

    This is the traditional method of mutating data in our reducers.

    这是在我们的Reducer中更改数据的传统方法。

    Reducer using Immer — produce

    使用Immer的Reducer —产生

    As shown below, the Object.assign() and the spread operators are replaced by produce and the code becomes easier to understand.

    如下所示,Object.assign()和散布运算符被生产替换,并且代码变得更易于理解。

    Advanced usage using curried Producer

    使用咖喱生产者的高级用法

    Using curried Producer further reduces the code . It takes a function as first argument which means we get a pre-bound producer that only needs a state to produce the value from. Initial state can be provided as second argument here.

    使用curried Producer可以进一步减少代码。 它以函数作为第一个参数,这意味着我们得到了一个预绑定生产者,该生产者只需要一个状态即可从中产生值。 初始状态可以在此处作为第二个参数提供。

    Usage of useImmer hook

    使用的用途

    We also have a hook called “useImmer” if we want to use immer with react-hooks

    如果我们想将immer和hacks一起使用,我们还有一个名为“ useImmer”的钩子。

    yarn add use-immer

    The sample usage is as follows:

    用法示例如下:

    import { useImmer } from ‘use-immer’;const [todo, setTodos] = useImmer([]);const onAddTodo = (newTodo) => { setTodos(draft => { draft.push(newTodo); });}

    Conclusion

    结论

    Immer makes enforcing immutability very smooth. It makes life easier when mutating nested data structures. And as we saw, the APIs for immer are very simple, easy to use, easy to learn and have a clean and efficient syntax. The interoperability with standard JavaScript and performance improvements just add icing on the top.

    Immer使强制不变性变得非常平滑。 当更改嵌套数据结构时,它使工作变得更轻松。 正如我们所看到的,沉浸式API非常简单,易于使用,易于学习,并且语法简洁高效。 与标准JavaScript的互操作性和性能改进仅在顶部添加了锦上添花。

    If you want to check out the entire code, please visit https://github.com/Nam92rata/Todo-app-with-Immer

    如果您想查看整个代码,请访问https://github.com/Nam92rata/Todo-app-with-Immer

    Thanks for reading !

    谢谢阅读 !

    翻译自: https://medium.com/mirafra-sw-engineering/achieving-immutability-using-immer-d5147b3f2ae

    怎么实现边侧栏不变

    相关资源:侧栏跟随滚动的简单实现代码
    Processed: 0.010, SQL: 8