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 .


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

查看所有标签

猜你喜欢:

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

操作系统基础教程

操作系统基础教程

戴维斯 / 第1版 (2006年7月1日) / 2006-7 / 34.0

这是一本关于操作系统基本原理的教科书,其最大特点就是从操作系统的分层概念出发,深入浅出地介绍了操作系统的基本概念和基本框架。本书可以作为高等院校非计算机专业相关课程的教材或参考书,也适合具有高中以上数学基础的计算机用户自学,还可以作为社会上计算机培训机构的教材。对所有想了解计算机操作系统,但又不需要或不打算深入学习其理论和实现细节的读者来说,本书是一本极具价值的入门指导书。一起来看看 《操作系统基础教程》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

SHA 加密
SHA 加密

SHA 加密工具

html转js在线工具
html转js在线工具

html转js在线工具