mobx computed getter 从未被评估

mobx computed getter is never evaluated

那是我的stackblitz/codepen:https://stackblitz.com/edit/svgtest?file=MountingViewModel.tsx

 import { observable, computed } from 'mobx';

export class MountingViewModel  
{
  constructor(isSelected: boolean, id: string, callback: (mounting: string) => any)
  {
    this.isSelected = isSelected;
    this.id = id;
    this.callback = callback;
  }

  @observable public isSelected: boolean;
  public id: string;
  public callback: Function;

  @computed get opacity() : number
  {
    console.log(this.isSelected);
    return this.isSelected ? 0.2 : 1.0;
  }
}

当我点击 red/blue 矩形时,getter opacity() 永远不会被点击。

这是为什么?

Why is that?

因为你在传播实例,例如<Roof {...this.allMountings.find(x => x.id === "roof") } />

Spread 不调用吸气剂:

class Foo { 
  x = 123;
  get y() {
    return 456
  }
}

console.log({ ...new Foo() }); // {x:123} NO `y`