【问题标题】:Immutable.js conditionally update MapImmutable.js 有条件地更新 Map
【发布时间】:2019-07-10 09:59:13
【问题描述】:
const state = fromJS({
  poolName: {
    poolNameCost:
    poolNamePercentage:
    poolNameShare:
  }
})

poolName 因操作而异。

如果其中任何一个更新,我必须更新所有属性 poolNameCost, poolNamePercentage, poolNameShare

我愿意

const { poolName, val, fieldSuffix, initialCost, initialShare } = action.payload;
state.update(`${poolName}`,
  items => ({
    ...items,
    [`${poolName}Cost`]() {
      if (suffix === 'Share') return (val / initialCost) * initialShare;
      if (suffix === 'Percentage') return (val / initialCost) * 100;
      return val
    },
    [`${poolName}Share`]() { //.....// },
    [`${poolName}Percentage`]() { //.....// },
  })
)

我得到一个空对象poolName = {}。为什么会这样?

上面的代码是下面代码的重构版本,效果很好。

代码,

 (suffix === 'Cost') &&
 state.update(`${poolName}`,
  items => ({
    ...items,
    [`${poolName}Share`]: (val / initialCost) * initialShare,
    //...similarly for other sibling property of `Share` in `poolName`...//
  })
 )

值正确更新。

【问题讨论】:

    标签: javascript immutable.js


    【解决方案1】:

    线条

    [`${poolName}Cost`]() {
          if (suffix === 'Share') return (val / initialCost) * initialShare;
          if (suffix === 'Percentage') return (val / initialCost) * 100;
          return val
    }, 
    

    在代码中调用时返回函数本身。所以我把它们改成了IIFE,像这样

    [`${poolName}Cost`]: (function() {
          if (suffix === 'Share') return (val / initialCost) * initialShare;
          if (suffix === 'Percentage') return (val / initialCost) * 100;
          return val
    })(),
    

    现在它在评估后返回基础值。

    有没有更好的方法来达到这个结果?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 1970-01-01
      • 2018-03-08
      • 2019-10-21
      相关资源
      最近更新 更多