简单定义一个生命周期
简单定义一个拥有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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通