当前位置 : 主页 > 网页制作 > React >

如何在MobX存储中跟踪嵌套对象

来源:互联网 收集:自由互联 发布时间:2021-06-15
让我留下来通过API调用加载myObject: myObject = { fieldA: { details: 'OK', message: 'HELLO' }, fieldB: { details: 'NOT_OK', message: 'ERROR' },} 只有每个字段的详细信息和消息都可以更改.我希望这个对象在Mo
让我留下来通过API调用加载myObject:

myObject = {
  fieldA: { details: 'OK', message: 'HELLO' },
  fieldB: { details: 'NOT_OK', message: 'ERROR' },
}

只有每个字段的详细信息和消息都可以更改.我希望这个对象在MobX存储中是可观察的(属性?将在下面定义).我有一个简单的React组件,它从商店中读取两个字段:

@observer
class App extends Component {
  store = new Store();

  componentWillMount() {
    this.store.load();
  }

  render() {
    return (
      <div>
        {this.store.fieldA && <p>{this.store.fieldA.details}</p>}
        {this.store.fieldB && <p>{this.store.fieldB.details}</p>}
      </div>
    );
  }
}

我读了this page试图了解MobX的反应,但仍然没有明确的想法.具体来说,下面4家商店中哪一家可以使用,为什么?

1 /

class Store1 = {
  @observable myObject = {};

  @action setMyObject = object => {
    this.myObject = object;
  }

  load = () => someAsyncStuff().then(this.setMyObject);
}

2 /

class Store2 = {
  @observable myObject = {};

  @action setMyObject = object => {
    this.myObject.fieldA = object.fieldA;
    this.myObject.fieldB = object.fieldB;
  }

  load = () => someAsyncStuff().then(this.setMyObject);
}

3 /

class Store3 = {
  @observable myObject = { fieldA: {}, fieldB: {} };

  @action setMyObject = object => {
    this.myObject = object;
  }

  load = () => someAsyncStuff().then(this.setMyObject);
}

4 /

class Store4 = {
  @observable myObject = { fieldA: {}, fieldB: {} };

  @action setMyObject = object => {
    this.myObject.fieldA = object.fieldA;
    this.myObject.fieldB = object.fieldB;
  }

  load = () => someAsyncStuff().then(this.setMyObject);
}
除解决方案2外,以上所有方法都有效.
那是因为如Mobx文档中描述的那样:

When passing objects through observable, only the properties that
exist at the time of making the object observable will be observable.
Properties that are added to the object at a later time won’t become
observable, unless extendObservable is used.

在第一个解决方案中,您再次使用返回对象中已存在的属性重新分配对象.
在3和4中,您使用这2个属性初始化了对象,因此它可以正常工作.

另外我认为在您的组件示例中,您打算像这样使用它(否则,它将无法以任何方式工作):

render() {
    const { myObject } = this.store;

    return (
      <div>
        {myObject && myObject.fieldA && <p>{myObject.fieldA.details}</p>}
        {myObject && myObject.fieldB && <p>{myObject.fieldB.details}</p>}
      </div>
    );
}
网友评论