反应状态作为计算状态取决于其他状态 属性

React state as compute state depend on other state property

state = {
   tips [{active: false, amount: 10}, {active: true, amount: 50}, {active: false, amount: 10}]
   active_tip_amount: // compute logic //
}

有没有什么方法可以active_tip_amout根据活动提示进行计算?

this.state.active_tip_amout 对于上面的情况应该是 50 它是根据 this.state

计算的

我建议 active_tip_amount 可能不需要存储在状态中。

如果您正在使用派生值,在需要它们时计算它们通常更简单,而不是在它发生变化时试图使它们与其他状态保持同步。

在这种情况下,您可以编写一个 getter(或方法)来计算当前状态的活跃小费金额,然后在需要访问计算值时调用它。

class TipsView extends Component {
  state = {
    tips [{active: false, amount: 10}, {active: true, amount: 50}, {active: false, amount: 10}]
  }

  get active_tip_amount() {
    let activeTip = this.state.tips.find(tip => tip.active);
    if (activeTip) {
      return activeTip.amount;
    } else {
      return 0;
    }
  }

  render() {
    // use the active amount here
    this.active_tip_amount
  }
}

这使您可以更灵活地计算该值,包括从 props 派生它(或者甚至使用函数而不是 getter 并对其进行参数化)。

如果您有理由相信按需计算值会减慢您的应用程序速度(在这种情况下不太可能),那么您始终可以记住计算它的函数。

阅读 Redux 如何鼓励人们使用 memoized selectors 解决此类问题,您可能会觉得很有趣。同样的原则也适用于 React 组件状态。