Is Immutable.js scary? I'll show you how to get started

原文 - Immutable.js is intimidating. Here’s how to get started.

You know from many sources that you should use Immutable . You want to use it too, but aren't sure why. And when you look at the official documentation , the first code snippet that catches your eye is:

identity<T>(value: T): T

You're thinking: uh...let's forget it.

This is a simple and quick article to get you started Immutable, and you won't be disappointed.

A year ago, at Pilcro , I recommended it to the development team Immutable. This has proven to be the wisest decision so far. Our applications are now more readable, more robust, less buggy, and more predictable.

Base

Convert standard jsdata formats toImmutable

In js, we know two common data types: Object{} and Array[] . ImmutableThe idea:

  • Object{} becomes MapMap({})
  • Array[] becomes ListList([])

To be more specific, use the Immutableprovided Mapand functions:ListfromJS

import { Map, List, fromJS } from 'immutable';
// 原生 js 数据类型
const person = {
  name: 'Will',
  pets: ['cat', 'dog']
};
// 等同于 Immutable 中的:
const immutablePerson = Map({
  name: 'Will',
  pets: List(['cat', 'dog'])
});
// 或者 ...
const immutablePerson = fromJS(person);

formJSis a very useful function that converts nested data structures into Immutableobjects. It creates Mapsand sums itself based on the data during the conversion process Lists.

ImmutableConvert to Standard jsData Format

To Immutableget back your standard jsdata format from an object, you just call Immutablethe object's toJSfunction:

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

Data structures should be considered native jsdata structures, or Immutableobjects

start usingImmutable

Before explaining why Immutableit is useful, here are three code snippets that show you Immutablehow to help you.

Get non-existing data value from nested data structure

First, native js:

const data = { my: { nested: { name: 'Will' } } };
const goodName = data.my.nested.name;
console.log(goodName); // 打印 Will
const badName = data.my.lovely.name;
// throws error: 'Cannot read name of undefined'
// 'lovely' 属性不存在,所以报错

Here's another look Immutable:

const data = fromJS({ my: { nested: { name: 'Will' } } });
const goodName = data.getIn(['my', 'nested', 'name']);
console.log(goodName); // 打印 Will
const badName = data.getIn(['my', 'lovely', 'name']);
console.log(badName); // 打印 undefined - 不会抛出异常

In the above example, the native jscode would throw an exception, but Immutableit would not.

This is because we use getIn()functions to get nested data values. The key path to the data value doesn't exist (in other words, the object is not the nested structure you expect), it just returns undefinedand doesn't throw an exception.

You don't have to nest like this to check if a data value exists:

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

This simple feature makes your code more readable, concise and more robust.

chain operation

First, native js:

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

Here's another look Immutable:

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

Because of List.pushreturning the result after the operation, we can continue the 链式operation later, and the function of the original array pushreturns the length of the new array after the operation.

This is a very simple example of chaining operations, but it illustrates the Immutablepower of this.

This allows you to handle various data manipulations in a functional and concise manner.

ImmutableOperations on objects always return the result of the operation

immutable data

It's called 不可变, so we need to discuss why this is important.

For example, you Immutablecreate an object and update it, but its initial data structure remains the same. This is it 不可变.

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

In this example, we can see that the original dataobject has not changed. This means that when you update its nameproperty value Susie, there is no unpredictable behavior.

This simple feature is very powerful, especially when you're building complex applications. This is Immutablethe core.

Operations on Immutableobjects do not change the original object, but create a new object

why Immutableit is useful

Some of Facebook 's engineers have compiled some of the benefits of using it on the front page of the documentation , but it's a bit confusing. ImmutableHere are some I put together 为什么你应该开始使用Immutable:

Your data structure is predictable

Because your data structure is Immutable, you know exactly how your data structure operates. In complex web applications, this means UIthat no additional, hilarious re-rendering issues will occur when you make very small changes to the data structure of .

Robustness of data manipulation

By using Immutableto manipulate data, it is very difficult for you to make mistakes in these operations. ImmutableDo a lot of dirty work for you: 捕获异常, 提供默认值and 开箱即用的创建嵌套数据结构.

Clean and readable code

ImmutableFunctional design may be confusing to you at first, but once you get the hang of it, chaining function calls will make your code less readable and more readable. This helps the team keep the code consistent.

follow-up study

Admittedly, Immutablethe learning curve isn't very smooth, but it's well worth it. Get startedThe study is just an appetizer.

Here are some of the caveats mentioned earlier. ImmutableUsing it is as easy as a duck in water if you take it to heart .

  • Data structures should be considered native jsdata structures, or Immutableobjects
  • ImmutableOperations on objects always return the result of the operation
  • Operations on Immutableobjects do not change the original object, but create a new object

good luck!

If you like this article, please go to the original article like and share it with others, and welcome to visit our company website Pilcro.com . PilcroIs a brand design software.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325377631&siteId=291194637