当前位置:网站首页>Immutable learning road -- farewell to traditional copy
Immutable learning road -- farewell to traditional copy
2022-06-25 04:36:00 【Bump】
Immutable【 Say goodbye to traditional copy 】
First episode :CSDN Bump , knowledge has no limit
cloudy 30°
The greatest test of courage on earth is to bear defaet without losing heart.
2022/6/24
immutable
It is a third-party library that replaces the traditional copy method
advantage :
- Operating on a new object does not affect the data of the original object
- Good performance
Install and use
1. download
npm i immutable
2. Import
import {Map} from 'immutable'
Map
grammar :
Map( object )
assignment :
set(" Property name "," The new value ")
Value :
get(" Property name ")
toJS()
Back to normal object
import React, {
Component } from 'react';
/** * 1. download npm i immutable * 2. Import import {Map} from 'immutable' */
import {
Map} from 'immutable'
var obj={
name:" Bump ",
age:20
}
var objImmu=Map(obj);
var newobjImmu=objImmu.set("name","pengkeStudy");
// console.log(objImmu,newobjImmu)
//get(' attribute ') Get value
console.log(objImmu.get("name"),newobjImmu.get("name"));
//toJS Back to normal object
console.log(objImmu.toJS(),newobjImmu.toJS());
/* // Writing a class Immu02 extends Component { state={ info:Map({ name:" Bump ", age:20 }) } render() { return ( <div> Immu02 <button onClick={()=>{ this.setState({ info:this.state.info.set('name',"pengkeStudy").set('age',1000) }) }}> Modify their values </button> {this.state.info.get("name")}---- {this.state.info.get("age")} </div> ); } }*/
// Write two
class Immu02 extends Component {
state={
info:{
name:" Bump ",
age:20
}
}
render() {
return (
<div>
Immu02
<button onClick={
()=>{
let old=Map(this.state.info)
let newImmu=old.set("name","pengkeStudy").set("age",10000)
this.setState({
info:newImmu.toJS()
})
}}> Modify their values </button>
{
this.state.info.name}----
{
this.state.info.age}
</div>
);
}
}
export default Immu02;
nesting Map
Map The objects in the middle object should be covered with
Map
Can pass map Of
get
Method to get the value and pass the value to the component ., Thus, the invalid refresh of components is perfectly solved
shouldComponentUpdate
Make a judgment and decide whether to refresh
import React, {
Component } from 'react';
import {
Map} from 'immutable'
class Immu03 extends Component {
state={
info:Map({
name:" Bump ",
age:20,
hobbit:Map({
likeone:" motion ",
liketwo:" Study "
})
})
}
render() {
return (
<div>
Immu03
<button onClick={
()=>{
this.setState({
info:this.state.info.set("name"," Learn ")
})}}> modify </button>
{
this.state.info.get("name")}
<Child hobbit={
this.state.info.get("hobbit")} ></Child>
</div>
);
}
}
class Child extends Component{
shouldComponentUpdate(nextProps,nextState){
// Judge hobbit Whether the value of is updated
if(this.props.hobbit===nextProps.hobbit){
return false;
}
return true;
}
render(){
return(
<div>Child</div>
);
}
componentDidUpdate(){
console.log(" Subcomponents updated ");
}
}
export default Immu03;
List
You can use the attribute method of an array
import React, {
Component } from 'react';
import {
List} from 'immutable'
var arr=List([1,231,1])
let arr2=arr.push(4)// Does not affect the original object structure
let arr3=arr2.concat([12,323,123])
console.log(arr,arr2,arr3);
class Immu04 extends Component {
state={
favor:List([' having dinner ',' sleep ',' Study ',' motion '])
}
render() {
return (
<div>
Immu04
{
this.state.favor.map(item=>{
return <li key={
item}>{
item}</li>
})
}
</div>
);
}
}
export default Immu04;
Implement individual modification cases
import {
List,Map } from 'immutable';
import React, {
Component } from 'react';
class Immu05 extends Component {
state={
info:Map({
name:" Bump ",
location:Map({
province:" jiangxi ",
city:" Ji'an "
}),
hobbit:List([' sleep ',' Study ',' Tap the keyboard '])
})
}
render() {
return (
<div>
<h1> Edit personal information </h1>
<div>
<button onClick={
()=>{
this.setState({
info:this.state.info.set("name"," like to study ").set("location",this.state.info.get("location").set("city"," nanchang "))
})
}}> modify </button>
{
this.state.info.get("name")}
<br />
{
this.state.info.get("location").get("province")}-
{
this.state.info.get("location").get("city")}
{
this.state.info.get("hobbit").map((item,index)=><li key={
item}>{
item}<button onClick={
()=>{
// console.log(index);
this.setState({
info:this.state.info.set("hobbit",this.state.info.get("hobbit").splice(index,1))
})
}}> Delete </button></li>)
}
</div>
</div>
);
}
}
export default Immu05;
adopt fromJS、setIn、updateIn Improvement
fromJS
Convert a normal object to ImmutablesetIn()
Depth assignment , Parameter 1 is an array. Fill in the fields that need to be modified , Parameter 2 is the modified valueupdateIn()
Depth modification , Parameter 1 is an array. Fill in the fields that need to be modified , Parameter 2 is the callback function ( The parameter is the original object )
import {
fromJS } from 'immutable';
import React, {
Component } from 'react';
class Immu06 extends Component {
state={
info:fromJS({
name:" Bump ",
location:{
province:" jiangxi ",
city:" Ji'an "
},
hobbit:[' sleep ',' Study ',' Tap the keyboard ']
})
}
render() {
return (
<div>
<h1> Edit personal information </h1>
<div>
<button onClick={
()=>{
this.setState({
info:this.state.info.setIn(["name"]," like to study ").setIn(["location","city"]," nanchang ")//setIn(" Parameter 1 is an array "," Modified value ")
})
}}> modify </button>
{
this.state.info.get("name")}
<br />
{
this.state.info.get("location").get("province")}-
{
this.state.info.get("location").get("city")}
{
this.state.info.get("hobbit").map((item,index)=><li key={
item}>{
item}<button onClick={
()=>{
// console.log(index);
// this.setState({
// info:this.state.info.setIn(["hobbit",index],"")
// })
//updateIn( Objects that need to be modified , Callback function ( The parameter is the original object ))
this.setState({
info:this.state.info.updateIn(["hobbit"],(list)=>list.splice(index,1))
})
}}> Delete </button></li>)
}
</div>
</div>
);
}
}
export default Immu06;
That's the tuition Immutable~
边栏推荐
- Laravel document sorting 6. Response
- Laravel document sorting 10. Request life cycle
- cnpm : 无法加载文件 C:\Users\Administrator\AppData\Roaming\npm\cnpm.ps1,因为在此系统上禁止运行脚本。
- 什么是持久化?redis 持久化中的RDB和AOF是什么?
- Lecture record: data processing methods and applications of various spatial geodetic techniques
- Intel 13th generation core showed its true colors for the first time: 68mb cache improved significantly
- 2020.3.3 notes async/await and promise and Then processes and threads
- OOP栈类模板(模板+DS)
- CTF_ Web: deserialization learning notes (I) classes and objects in PHP
- Record of the 25th week
猜你喜欢
Basic use of OBS browser+ browser
CTF_ Web: basic 12 questions WP of attack and defense world novice zone
PHP extracts and analyzes table contents, and collects bidding information
Leetcode points to the leetcode road of offering II 091 house painting [dynamic planning] heroding
单元测试覆盖率
L'épée leetcode fait référence au chemin leetcode de l'offre II 091 pour peindre la maison [planification dynamique] heroding
CTF_ Web: how to recognize and evaluate a regular expression
English Grammar - pronunciation rules
OBS Browser+浏览器的基本使用
Gbase 8s overall architecture
随机推荐
EasyRecovery15非常好用的电脑数据恢复软件
Doubts about judging the tinyint field type of MySQL
PHP extracts and analyzes table contents, and collects bidding information
js的call()和apply()
PHP encapsulates curl to send get and post request methods, and uses
php封装curl发送get、post请求方法,并使用
GBASE 8s 总体架构
Office macro virus bounce shell experiment
GBASE 8s的数据导入和导出
2021.6.14 notes
GBase 8s 锁的分类
Record small knowledge points
LeetCode 劍指Offer II 091 粉刷房子[動態規劃] HERODING的LeetCode之路
kenlm
GBASE 8s 索引R树
领导:谁再用 Redis 过期监听实现关闭订单,立马滚蛋!
Cnpm: unable to load file c:\users\administrator\appdata\roaming\npm\cnpm PS1 because running scripts is prohibited on this system.
OOP栈类模板(模板+DS)
Synchronous and asynchronous functions (callback function, promise, generator, async/await)
GBASE 8s存儲過程語法結構