React MVC架构Model类函数中temp变量调用后更新值留存问题求助
问题根因
你当前的temp是函数内部声明的局部变量,每次调用该函数都会重新执行初始化赋值var temp = 1,上次调用修改后的temp值不会被留存,自然每次都是初始值1。
解决方案
因为你是在React Model类中使用,只需要把temp改为类的实例属性,把初始赋值逻辑移到类的构造函数中即可,修改示例如下:
class YourModel extends Model { constructor() { super() // 把temp定义为实例属性,初始化赋值1 this.temp = 1 // 其他原有初始化逻辑 } // 你原来的业务函数 yourFunction() { console.log("temp = "+ this.temp) let sPlanId = constant['SUBSCRIPTION_TIERS'][event_subscription.plan_id]; console.log("SPlanId = "+sPlanId) if(sPlanId - this.temp == 1 && sPlanId == 2) { fix_project_post_cnt = 4; this.temp = sPlanId; } else if(sPlanId - this.temp == 1 && sPlanId == 3) { fix_project_post_cnt = 5; this.temp = sPlanId; } else if(sPlanId - this.temp == 2 && sPlanId == 3) { fix_project_post_cnt = 9; this.temp = sPlanId; } else if(sPlanId - this.temp == 1 && sPlanId == 4) { fix_project_post_cnt = 10; this.temp = sPlanId; } else if(sPlanId - this.temp == 2 && sPlanId == 4) { fix_project_post_cnt = 15; this.temp = sPlanId; } else if(sPlanId - this.temp == 3 && sPlanId == 4) { fix_project_post_cnt = 19; this.temp = sPlanId; } // 其他原有逻辑 } }
可选优化
可以把冗余的多分支判断改为映射表,代码更简洁易维护:
// 提前定义映射规则,key为`差值,sPlanId`格式,value为对应的fix_project_post_cnt值 const planMap = { '1,2':4, '1,3':5, '2,3':9, '1,4':10, '2,4':15, '3,4':19 } // 函数内可以直接替换所有if else逻辑 const diff = sPlanId - this.temp const mapKey = `${diff},${sPlanId}` if(planMap[mapKey]){ fix_project_post_cnt = planMap[mapKey] this.temp = sPlanId }
补充说明
如果你用的是支持state的状态管理Model(比如dva、rematch等),也可以把temp存在Model的state字段中,每次更新通过reducer修改temp的值,同样可以实现持久化。
内容的提问来源于stack exchange,提问作者pankaj verma
相关产品推荐
相关产品推荐

