跳到主要内容

Immutable

Immutable Data 就是一旦创建,就不能再被更改的数据。对于 Immutable 对象的任何修改或添加删除操作都会返回一个新的Immutable对象。Immutable 实现的原理是Persistent Data Structure(持久化数据结构),也就是使用旧数据创建新数据时,要保证旧数据同时可用且不变,同时为了避免deepCopy 把所有的节点都复制一遍带来的性能损耗。Immutable 使用了 Structural Sharing(结构共享) , 即如果对象树中一个节点发生变化,只修改这个节点和受它影响的父节点,其他节点则进行共享。

API


is

语法

import { fromJS,is } from "immutable";

const obj1 = fromJS({name:"柏拉文"});
const obj2 = fromJS({name:"柏拉文"});

const result = is(obj1,obj2);
console.log(result); // true

map

语法

import { Map } from "immutable";

const obj = Map({ name: "柏拉图" });
const obj1 = obj.set("age", 23);
const obj2 = obj1.update("age", (value) => value + 1);
const obj3 = obj2.merge({ like: "学习" });
const obj4 = obj3.setIn(['other','height'],183);
const obj5 = obj4.updateIn(['other','height'],value=>value+1);
const obj6 = obj5.mergeIn(["user"], { weight: 120 });

console.log(obj);
console.log(obj1);
console.log(obj2);
console.log(obj3);
console.log(obj4);
console.log(obj5);
console.log(obj6);

list

语法

import { List } from "immutable";

const array = List([1, 2, 3]);
console.log(array);
console.log(array.size);

const array1 = array.push(4);
console.log(array1);
console.log(array1.size);

const array2 = array1.update(2, (value) => value * 2);
console.log(array2);
console.log(array2.size);

const array3 = array2.pop();
console.log(array3);
console.log(array3.size);

const array4 = array3.filter((value) => value === 3);
console.log(array4);
console.log(array4.size);

const item1 = array4.get(1);
console.log(item1);

fromJS

语法

import { fromJS } from "immutable";

const obj = fromJS({ name: "柏拉图" });
const obj1 = obj.set("age", 23);
const obj2 = obj1.update("age", (value) => value + 1);
const obj3 = obj2.merge({ like: "学习" });
const obj4 = obj3.setIn(['other','height'],183);
const obj5 = obj4.updateIn(['other','height'],value=>value+1);
const obj6 = obj5.mergeIn(["user"], { weight: 120 });

console.log(obj);
console.log(obj1);
console.log(obj2);
console.log(obj3);
console.log(obj4);
console.log(obj5);
console.log(obj6);

toJS

toJSON

toObject

语法


React 类组件使用

import React from "react";
import ReactDOM from "react-dom";
import { Map, is } from "immutable";

class App extends React.Component {
constructor(props) {
super(props);
this.state = {
a: Map({
b: "b",
c: "c",
}),
};
}
handleClick(v = "") {
const a = this.state.a.updateIn(["b"], (value) => value + v);
this.setState({
a,
});
}
shouldComponentUpdate(nextProps, nextState) {
if (is(nextState.a, this.state.a)) {
return false;
}
return true;
}
render() {
const { a } = this.state;
console.log("渲染");
return (
<div>
<h3>React 不可变状态</h3>
{a.getIn(["b"])}
<button onClick={() => this.handleClick()}>改变相同的值</button>
<button onClick={() => this.handleClick("修改")}>改变不同的值</button>
</div>
);
}
}

ReactDOM.render(<App />, document.getElementById("root"));