You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 08:27:04