简单定义一个生命周期

简单定义一个拥有create,willStateUpdate和shouldStateUpdate三个类似生命周期的类,名字随意,不要介意

复制代码
class State {
  constructor() {
    this.state = { hehe: "9" };
    //第一次调用
    this.created(this.state);
  }
  setState(newValue) {
    //调用生命周期
    this.willStateUpdate(newValue);
    const upDate = this.shouldStateUpdate(newValue);
    if (upDate) {
      const preValue = this.state;
      this.state = {
        ...preValue,
        ...newValue,
      };
    } else {
      console.log("没有数据改变");
    }
  }

  //定义生命周期
  willStateUpdate() {
    // 默认啥也不做
  }
  shouldStateUpdate() {
    // 默认返回true,一直都是更新
    return true;
  }
}
//子类继承父类,对方法具体实现
class User extends State {
  created() {
    console.log("我是创建前调用", this);
  }
  willStateUpdate(nextState) {
    const oldValue = this.state;
    const li = [1, 2, 3, 4];
    this.state = {
      ...oldValue,
      li,
    };
  }
  shouldStateUpdate(nextState) {
    if (JSON.stringify(nextState) === JSON.stringify(this.state)) {
      console.log("值相等,不更新");
      return false;
    } else {
      console.log("值不相等,更新");
      return true;
    }
  }
}

const user = new User();
user.setState({ name: "李四", age: 19 });
console.log(user.state);
复制代码

输出:

我是创建前调用 User { state: { hehe: '9' } }
值不相等,更新
{ hehe: '9', li: [ 1, 2, 3, 4 ], name: '李四', age: 19 }

posted @   lijun12138  阅读(29)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示