原文 - 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 js
data formats toImmutable
In js
, we know two common data types: Object{}
and Array[]
. Immutable
The idea:
- Object
{}
becomes MapMap({})
- Array
[]
becomes ListList([])
To be more specific, use the Immutable
provided Map
and functions:List
fromJS
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);
formJS
is a very useful function that converts nested data structures into Immutable
objects. It creates Maps
and sums itself based on the data during the conversion process Lists
.
Immutable
Convert to Standard js
Data Format
To Immutable
get back your standard js
data format from an object, you just call Immutable
the object's toJS
function:
import { Map } from 'immutable';
const immutablePerson = Map({ name: 'Will' });
const person = immutablePerson.toJS();
console.log(person); // 打印 { name: 'Will' };
Data structures should be considered native
js
data structures, orImmutable
objects
start usingImmutable
Before explaining why Immutable
it is useful, here are three code snippets that show you Immutable
how 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 js
code would throw an exception, but Immutable
it 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 undefined
and 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.push
returning the result after the operation, we can continue the 链式
operation later, and the function of the original array push
returns the length of the new array after the operation.
This is a very simple example of chaining operations, but it illustrates the Immutable
power of this.
This allows you to handle various data manipulations in a functional and concise manner.
Immutable
Operations 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 Immutable
create 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 data
object has not changed. This means that when you update its name
property value Susie
, there is no unpredictable behavior.
This simple feature is very powerful, especially when you're building complex applications. This is Immutable
the core.
Operations on
Immutable
objects do not change the original object, but create a new object
why Immutable
it 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. Immutable
Here 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 UI
that 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 Immutable
to manipulate data, it is very difficult for you to make mistakes in these operations. Immutable
Do a lot of dirty work for you: 捕获异常
, 提供默认值
and 开箱即用的创建嵌套数据结构
.
Clean and readable code
Immutable
Functional 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, Immutable
the learning curve isn't very smooth, but it's well worth it. Get started
The study is just an appetizer.
Here are some of the caveats mentioned earlier. Immutable
Using it is as easy as a duck in water if you take it to heart .
- Data structures should be considered native
js
data structures, orImmutable
objects Immutable
Operations on objects always return the result of the operation- Operations on
Immutable
objects 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 . Pilcro
Is a brand design software.