如何在MobX存储中跟踪嵌套对象
让我留下来通过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文档中描述的那样:
在第一个解决方案中,您再次使用返回对象中已存在的属性重新分配对象. 另外我认为在您的组件示例中,您打算像这样使用它(否则,它将无法以任何方式工作): render() { const { myObject } = this.store; return ( <div> {myObject && myObject.fieldA && <p>{myObject.fieldA.details}</p>} {myObject && myObject.fieldB && <p>{myObject.fieldB.details}</p>} </div> ); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |