One Cool Trick to Simplify Reducer Functions

栏目: IT技术 · 发布时间: 4年前

One Cool Trick to Simplify Reducer Functions

Redux is an amazing tool if you take the time to get to know it. One of the things about Redux that commonly trips people up is that reducers must be pure functions.

A pure function is a function which:

  1. Given same arguments, always returns the same result, and
  2. Has no side-effects (e.g., it won’t mutate its input arguments).

The problem is that sometimes a reducer needs to make a complicated change to some input state, but you can’t just mutate the state argument without causing bugs.

The solution is a handy tool called Immer . In this video, I’ll introduce you to Immer and show you how to use it to reduce the complexity of your reducer code. With one or two small reducers, the difference is pretty subtle, but on a large project, it can significantly simplify your application code.

Here’s an example. Imagine you’re building a social network, and you need to keep track of posts that a user has liked. When they like a post, you add a like object to the user’s likes collection. That might look something like this:

Notice what we’re returning from the like.type case: Mixing bits of the payload into a nested property of the state object using the JavaScript object spread syntax: ...state and ...state.likes on lines 19–25.

After immer, you can simplify that part to a one-liner (line 21):

The produce function returns a partial application (a function which has been partially applied to its arguments) which then takes the arguments of the reducer function. You pass it a callback function which takes a draft of the state object instead of the real state object. You’re free to mutate that object as if it were any other mutable object in JavaScript. No more spreading nested properties to avoid mutating the input argument.

After your callback function runs, Immer compares the draft to the original state and then builds a new object with your changes applied, so your function feels like it’s mutating, but still behaves like a pure function. You get the best of both worlds: The simplicity of mutation with the benefits of immutability.

Next Steps

EricElliottJS.com has in-depth lessons on topics like pure functions, immutability, partial applications, and other functional and object oriented programming concepts.

Subscribe on YouTube .


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

智能Web算法

智能Web算法

Haralambos Marmanis、Dmitry Babenko / 阿稳、陈钢 / 电子工业出版社 / 2011-11 / 65.00元

本书涵盖了五类重要的智能算法:搜索、推荐、聚类、分类和分类器组合,并结合具体的案例讨论了它们在Web应用中的角色及要注意的问题。除了第1章的概要性介绍以及第7章对所有技术的整合应用外,第2~6章以代码示例的形式分别对这五类算法进行了介绍。 本书面向的是广大普通读者,特别是对算法感兴趣的工程师与学生,所以对于读者的知识背景并没有过多的要求。本书中的例子和思想应用广泛,所以对于希望从业务角度更好......一起来看看 《智能Web算法》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具