Skip to content

深拷贝与浅拷贝 #1

Open
Open
@livaha

Description

@livaha

Issues:由于对象已经进行了深拷贝,但却会影响到生命周期中的nextState
如:

  state={
    result:{
      wanping:"0",
    },    
  }

  shouldComponentUpdate(nextProps, nextState){
    /**为什么这里的nextState会跟this.state相同,对象的赋值不是已经深拷贝了吗 */
    console.log(JSON.stringify(this.state)===JSON.stringify(nextState)) //一真返回true
    return true
  }

/*赋值*/
  getVpnpassConfig=()=>{
    axios.ajax_post({
      data:{cgid:8 },
      url:posturl
    }).then((res)=>{
        if(res.restcode === 2000){
          /**这里只能用deepCopy去分别复制,不然就成了引用的了 */
            this.setState({
              result:deepCopy(res.result),
            })
        }
    })
  }

/*修改值 */
  handleSelectOnchange=name=>e=>{
    let {result} = this.state
    result[name] = e.target.value
    this.setState({
      result:result
    })
  }`
  

           const {result:{wanping}}=this.state

          <Select onChange={this.handleSelectOnchange("wanping")} value={wanping}>
            <option value ="0">{__('OFF')}</option>
            <option value ="1" >{__('ON')}</option>
          </Select>

每次修改都会影响到 shouldComponentUpdate(nextProps, nextState)里nextState的值,这是为什么呢

附深拷贝函数代码:

let util = ( ()=> {
    // 获取数据类型
    let getType=(obj)=> {
        let type = Object.prototype.toString.call(obj);
        return /object\s(.*)]/.exec(type)[1];
    };  
    let isType=(obj, type)=>{
        obj = getType(obj).toLowerCase();
        return obj === type;
    };  
    return {
        isType: isType
    }  
})();
  
// 将obj对象传入,return一个复制后的对象出来
export let deepCopy = (obj1) => {  
    // 若不是对象类型或是null类型,直接输出
    if (typeof obj1 !== 'object' || obj1 === null) {
        return obj1
    }  
    let i;
    // 根据目标是Array类型还是object来设置目标参数的类型
    let target = util.isType(obj1, 'array') ? [] : {};
    for (i in obj1) {
        // 判断当前复制的对象是否为对象类型数据
        if (typeof obj1[i] === 'object') {  
            deepCopy(obj1[i]);
        }
        target[i] = obj1[i]
    }
    return target
};
  

解决: 原来是需要深拷贝一下this.state的数据 ,才不会影响到下一个nextState的数据;
原因:意思是对象的拷贝不用通过this.setState就可以直接修改了this.state的内容了。。。

  handleSelectOnchange=name=>e=>{
  -  let {result} = this.state
 +   let result = deepCopy(this.state.result)
    result[name] = e.target.value
    this.setState({
      result:result
    })
  }

参考文章

- 浅拷贝与深拷贝

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions