原文 – 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, but aren’t sure why. When you look at the official documentation, the first code snippet you see is:

identity<T>(value: T): T
Copy the code

And you think, Uh… Forget it.

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

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

basis

standardjsData format conversion toImmutable

In JS, we know of two common data types: Object{} and Array[]. Immutable

  • Object{}intoMapMap({})
  • Array[]intoListList([])

More specifically, the Map, List, and fromJS functions that are provided by Immutable:

import { Map, List, fromJS } from 'immutable';
// Native JS data types
const person = {
  name: 'Will'.pets: ['cat'.'dog']};// Equivalent to Immutable:
const immutablePerson = Map({
  name: 'Will'.pets: List(['cat'.'dog'])});// 或者 ...
const immutablePerson = fromJS(person);
Copy the code

FormJS is a very useful function that converts nested data structures into Immutable objects. It creates Maps and Lists itself based on the data as it transforms.

ImmutableConversion to standardjsThe data format

To fetch your standard JS data format from Immutable, you simply call the toJS function on Immutable:

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

Data structures should be considered native JS data structures, or Immutable objects

Begin to useImmutable

Before explaining why Immutable is useful, let me give you three code snippet that show you how Immutable can help you.

Retrieves non-existent data values from nested data structures

First, native JS:

const data = { my: { nested: { name: 'Will'}}};const goodName = data.my.nested.name;
console.log(goodName); / / print Will
const badName = data.my.lovely.name;
// throws error: 'Cannot read name of undefined'
// The 'lovely' property does not exist, so an error is reported
Copy the code

Consider Immutable:

const data = fromJS({ my: { nested: { name: 'Will'}}});const goodName = data.getIn(['my'.'nested'.'name']);
console.log(goodName); / / print Will
const badName = data.getIn(['my'.'lovely'.'name']);
console.log(badName); // Prints undefined - does not throw an exception
Copy the code

In the example above, native JS code throws exceptions, but Immutable does not.

This is because we use the getIn() function to get nested data values. There is no key path for the data value (in other words, the object is not the nested structure you would expect), and it simply returns undefined without throwing an exception.

You don’t have to nest data values like the following:

if (data && data.my && data.my.nested && data.my.nested.name) { ...
Copy the code

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

The chain operation

First, native JS:

const pets = ['cat'.'dog'];
pets.push('goldfish');
pets.push('tortoise');
console.log(pets); // print ['cat', 'dog', 'piranere ', 'tortoise'];
Copy the code

Consider Immutable:

const pets = List(['cat'.'dog']);
const finalPets = pets.push('goldfish').push('tortoise');
console.log(pets.toJS()); // Prints ['cat', 'dog'];
console.log(finalPets.toJS()); // print ['cat', 'dog', 'piranere ', 'tortoise'];
Copy the code

Since list. push returns the result after the operation, we can continue the chain operation later, and the push function of the native array returns the length of the new array after the operation.

This is a very simple example of a chain operation, but it illustrates the power of Immutable.

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

An Immutable operation always returns the result of the operation

Immutable data

It’s called immutable, so we need to talk about why this is important.

For example, if you create an object using Immutable and update it, its original data structure remains the same. That’s immutable.

const data = fromJS({ name: 'Will' });
const newNameData = data.set('name'.'Susie');
console.log(data.get('name')); / / print 'Will'
console.log(newNameData.get('name')); / / print 'Susie'
Copy the code

In this example, we can see that the original data object has not changed. This means that when you update its name property value to Susie, it is not accompanied by unpredictable behavior.

This simple feature is very powerful, especially if you are building complex applications. This is the core of Immutable.

An operation on an Immutable object does not alter the original object, but creates a new one

whyImmutableIt is useful to

Some of facebook’s engineers have documented some of the benefits of using Immutable on the front page, but it’s a bit convoluted. Here are some of the reasons why you should start using Immutable:

Your data structure is predictable

Because your data structures are Immutable, you know exactly how your data structures operate. In complex Web applications, this means that when you make very small changes to the DATA structure of the UI, there are no additional, ironic re-rendering issues.

Robustness of data operations

By manipulating data Immutable, your operations are hard to get wrong. Immutable does a lot of the dirty work for you: catching exceptions, providing default values, and creating nested data structures right out of the box.

Concise and readable code

At first you might be confused by Immutable function design, but once you get the idea, chained function calls will make your code smaller and more readable. This helps the team keep the code consistent.

The follow-up study

Admittedly, the Immutable learning curve is not smooth, but it is well worth it. Learning is just an appetizer.

Here are some of the considerations mentioned earlier. Using Immutable, if you remember it, is as easy as a duck in water.

  • Data structures should be considered nativejsData structure, orImmutableobject
  • ImmutableAn operation on an object always returns the result of the operation
  • inImmutableAn operation on an object does not change the original object, but creates a new object

Good luck!

If you liked this article, please like it and share it with others, and please visit our website at Pilcro.com. Pilcro is a brand design software.