immutable.js_Immutable.js令人生畏。 这是入门方法。

immutable.js

by William Woodhead

威廉伍德黑德(William Woodhead)

Immutable.js令人生畏。 这是入门方法。 (Immutable.js is intimidating. Here’s how to get started.)

You hear that you should be using Immutable. You know you should, but you aren’t quite sure why. And when you go to the docs, the first snippet of code looks like this:

您听说应该使用Immutable 。 您知道应该这样做,但是您不确定为什么。 当您转到docs时 ,第一段代码如下所示:

identity<T>(value: T): T

You think: Nah… maybe another time.

您认为:不,也许是另一次。

So, here’s a simple and fast introduction to get you started with Immutable. You won’t regret it:

因此,这里有一个简单快速的介绍,可帮助您开始使用Immutable。 您不会后悔的:

At Pilcro, we introduced Immutable into our applications about 12 months ago. It has been one of the best decisions we have made. Our apps are now much more readable, robust, bug-free and predictable.

Pilcro ,大约12个月前,我们将Immutable引入了我们的应用程序。 这是我们做出的最佳决定之一。 现在,我们的应用程序更具可读性,健壮性,无错误且可预测。

基础 (The basics)

转换为不可变 (Converting into Immutable)

In normal JavaScript, we know two common data types: Object {} and Array [].

在普通JavaScript中,我们知道两种常见的数据类型: Object {}Array []

To translate these into Immutable:

要将它们转换为不可变的:

  • Object {} becomes Map Map({})

    对象 {} 成为Map Map({})

  • Array [] becomes List List([])

    数组 []成为列表 List([])

To convert normal JavaScript into Immutable, we can use the Map, List, or fromJS functions that Immutable provides:

要将普通JavaScript转换为Immutable,我们可以使用Immutable提供的MapListfromJS函数:

import { Map, List, fromJS } from 'immutable';
// Normal Javascript
const person = {  name: 'Will',  pets: ['cat', 'dog']};
// To create the equivalent in Immutable:
const immutablePerson = Map({  name: 'Will',  pets: List(['cat', 'dog'])});
// Or ...
const immutablePerson = fromJS(person);

fromJS is a useful function that converts nested data into Immutable. It creates Maps and Lists in the conversion.

fromJS是有用的函数,可将嵌套数据转换为Immutable。 它在转换中创建MapsLists

从不可变转换回普通JavaScript (Converting back from Immutable to normal JavaScript)

It is very simple to get your data back from Immutable to plain old JavaScript. You just call the .toJS() method on your Immutable object.

将您的数据从Immutable还原到普通的旧JavaScript非常简单。 您只需在Immutable对象上调用.toJS()方法。

import { Map } from 'immutable';
const immutablePerson = Map({ name: 'Will' });const person = immutablePerson.toJS();
console.log(person); // prints { name: 'Will' };

Keynote: Data structures should be thought of as EITHER plain JavaScript OR Immutable.

主题演讲: 数据结构应被视为普通JavaScript或不可变的。

开始使用不可变 (Start using Immutable)

Before explaining why Immutable is so useful, here are three simple examples of where Immutable can help you out right away.

在解释为什么Immutable如此有用之前,这里有三个简单的示例,它们说明Immutable可以立即为您提供帮助。

1.从对象获取嵌套值,而不检查其是否存在 (1. Getting a nested value from an object without checking if it exists)

First in normal JavaScript:

普通JavaScript中的第一个:

const data = { my: { nested: { name: 'Will' } } };
const goodName = data.my.nested.name;console.log(goodName); // prints Will
const badName = data.my.lovely.name;// throws error: 'Cannot read name of undefined'

And now in Immutable:

现在在不可变中:

const data = fromJS({ my: { nested: { name: 'Will' } } });
const goodName = data.getIn(['my', 'nested', 'name']);console.log(goodName); // prints Will
const badName = data.getIn(['my', 'lovely', 'name']);console.log(badName); // prints undefined - no error thrown

In the above examples, the normal JavaScript code throws an error, whereas the Immutable one does not.

在上面的示例中,普通JavaScript代码会引发错误,而Immutable则不会。

This is because we use the getIn() function to get a nested value. If the key path doesn’t exist (that is, the object isn’t structured as you thought), it returns undefined rather than throwing an error.

这是因为我们使用getIn()函数来获取嵌套值。 如果键路径不存在(也就是说,对象的结构不如您想象的那样),它将返回未定义的状态,而不是引发错误。

You don’t need to check for undefined values all the way down the nested structure like you would in normal JavaScript:

您不需要像在常规JavaScript中那样一直在嵌套结构中一直检查未定义的值:

if (data && data.my && data.my.nested && data.my.nested.name) { ...

This simple feature makes your code much more readable, less wordy, and much more robust.

这个简单的功能使您的代码更具可读性,更少的冗长且更健壮。

2.链接操作 (2. Chaining manipulations)

First in normal JavaScript:

普通JavaScript中的第一个:

const pets = ['cat', 'dog'];pets.push('goldfish');pets.push('tortoise');console.log(pets); // prints ['cat', 'dog', 'goldfish', 'tortoise'];

Now in Immutable:

现在处于不可变状态:

const pets = List(['cat', 'dog']);const finalPets = pets.push('goldfish').push('tortoise');
console.log(pets.toJS()); // prints ['cat', 'dog'];
console.log(finalPets.toJS());// prints ['cat', 'dog', 'goldfish', 'tortoise'];

Because List.push() returns the result of the operation, we can “chain” the next operation right onto it. In normal JavaScript, the push function returns the length of the new array.

由于List.push()返回操作的结果,因此我们可以将下一个操作“链接”到该操作上。 在普通JavaScript中, push函数返回新数组的长度。

This is a very simple example of chaining, but it illustrates the real power of Immutable.

这是一个非常简单的链接示例,但它说明了Immutable的真正功能。

This frees you up to do all sorts of data manipulation in a manner that is more functional and more concise.

这样可以使您腾出更多功能,更简洁地进行各种数据操作。

Keynote: Operations on an Immutable object return the result of the operation.

主题演讲:对不可变对象的操作返回操作结果。

3.不变的数据 (3. Immutable data)

It’s called Immutable after all, so we need to talk about why this is important!

毕竟它被称为不可变的,所以我们需要谈论为什么这很重要!

Let’s say you create an Immutable object and you update it — with Immutable, the initial data structure is not changed. It is immutable. (lower case here!)

假设您创建了一个不可变对象并对其进行了更新-使用不可变对象,初始数据结构不会更改。 这是一成不变的。 (这里小写!)

const data = fromJS({ name: 'Will' });const newNameData = data.set('name', 'Susie');
console.log(data.get('name')); // prints 'Will'console.log(newNameData.get('name')); // prints 'Susie'

In this example we can see how the original “data” object is not changed. This means that you will not get any unpredictable behaviour when you update the name to “Susie.”

在这个例子中,我们可以看到原始的“数据”对象是如何不变的。 这意味着当您将名称更新为“ Susie”时,您将不会出现任何不可预测的行为。

This simple feature is really powerful, particularly when you are building complex applications. It is the backbone of what Immutable is all about.

这个简单的功能非常强大,尤其是在构建复杂的应用程序时。 这是不可变的全部内容的骨干。

Keynote: Operations on an Immutable object do not change the object, but instead create a new object.

主题演讲对不可变对象的操作不会更改对象,而是创建一个新对象。

为什么不可变是有用的 (Why Immutable is useful)

The developers at Facebook sum up the benefits on the homepage of the docs, but it’s quite tricky to read. Here is my take on why you should start using Immutable:

Facebook的开发人员在文档的首页 总结了这些好处,但是阅读起来非常棘手。 这是我对为什么应该开始使用Immutable的看法:

您的数据结构变化可预测 (Your data structures change predictably)

Because your data structures are immutable, you are in charge of how your data structures are operated upon. In complex web applications, this means you don’t get funny re-rendering issues when you change a bit of data that is being accessed for the UI.

因为您的数据结构是不可变的,所以您负责数据结构的操作方式。 在复杂的Web应用程序中,这意味着当您更改一些正在为UI访问的数据时,您不会遇到有趣的重新渲染问题。

强大的数据处理 (Robust data manipulation)

By using Immutable to manipulate data structures, your manipulations themselves are much less error-prone. Immutable does a lot of the hard work for you — it catches errors, offers default values, and builds nested data structures out-of-the-box.

通过使用Immutable来操纵数据结构,您的操纵本身就不那么容易出错了。 Immutable为您完成了许多艰苦的工作-它捕获错误,提供默认值并开箱即用地构建嵌套的数据结构。

简洁易读的代码 (Concise readable code)

The functional design of Immutable can be confusing at first, but once you get used to it, function chaining makes your code much shorter and more readable. This is great for teams working on the same code base.

首先,Immutable的功能设计可能会令人困惑,但是一旦您习惯了它,函数链接会使您的代码更短,更易读。 这对于在相同代码库上工作的团队非常有用。

下一步 (Next steps)

The learning curve is undeniably tricky with Immutable, but really worth it. Get started just having a play around.

无可否认,学习曲线无疑是棘手的,但确实值得。 开始玩耍吧。

Here are the keynotes that were noted as we went through. If you can keep these in your mind, you will take to Immutable like a duck to water!

以下是我们讨论过的主题演讲。 如果您能牢记这些,您将像鸭子一样进入不可变!

  1. Data structures should be thought of as EITHER plain JavaScript OR Immutable.

    数据结构应被视为普通JavaScript或不可变的。
  2. Operations on an Immutable object return the result of the operation.

    对不可变对象的操作将返回操作结果。
  3. Operations on an Immutable object do not change the object itself, but instead create a new object.

    对不可变对象的操作不会更改对象本身,而是会创建一个新对象。

Good luck!

祝好运!

If you liked this story, please ? and please share with others. Also please check out my company pilcro.com. Pilcro is brand software for G-Suite — for marketers and brand agencies.

如果您喜欢这个故事,请? 并请与他人分享。 还请查看我的公司p ilcro.com。 Pilcro是G-Suite的品牌软件-适用于营销商和品牌代理。

翻译自: https://www.freecodecamp.org/news/immutable-js-is-intimidating-heres-how-to-get-started-2db1770466d6/

immutable.js

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值