当前位置:网站首页>Immutable learning road -- farewell to traditional copy

Immutable learning road -- farewell to traditional copy

2022-06-25 04:36:00 Bump

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 Immutable
  • setIn() Depth assignment , Parameter 1 is an array. Fill in the fields that need to be modified , Parameter 2 is the modified value
  • updateIn() 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~

原网站

版权声明
本文为[Bump]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206250300219954.html