Javascript 使用组件和其他存储中其他存储的react mobx操作
在我的react原生应用程序中,我想使用mobx进行状态管理,我的商店被划分为多个商店/文件,因为我想能够从其他商店调用商店操作,所以我正在实现一个GlobalStore,在这里我实例化了其他商店 我希望能够从我的组件中执行类似的操作Javascript 使用组件和其他存储中其他存储的react mobx操作,javascript,reactjs,native,mobx,Javascript,Reactjs,Native,Mobx,在我的react原生应用程序中,我想使用mobx进行状态管理,我的商店被划分为多个商店/文件,因为我想能够从其他商店调用商店操作,所以我正在实现一个GlobalStore,在这里我实例化了其他商店 我希望能够从我的组件中执行类似的操作 import { PostStore } from '../stores/PostStore.js' import { UserStore } from '../stores/UserStore.js' import { VenueStore } from
import { PostStore } from '../stores/PostStore.js'
import { UserStore } from '../stores/UserStore.js'
import { VenueStore } from '../stores/VenueStore.js'
class GlobalStore
{
postStore = new PostStore(this);
userStore = new UserStore(this);
venueStore = new VenueStore(this);
}
export default new GlobalStore;
这使得使用react本机上下文提供程序API,我可以使用globalStore作为链接调用所有组件中的每个存储操作:
在任何组件中,我都可以做到:
globalStore.postStore.listPosts()
但是,我仍然不确定如何从其他商店中访问其他商店操作
如果在postStore中我想使用spinnerStore(显示axios呼叫挂起、错误或成功状态),该怎么办
在这里喷丝头存储将是未定义的
但是,我仍然不确定如何从其他商店中访问其他商店操作
实例化一个存储时,可以将其一个属性指定给另一个存储实例。这就是您在示例中包含的内容
class-Foo{
构造函数(实例){
this.instance=instance
}
}
类条{}
const foo=new foo(new Bar());
foo.instance instanceof Bar;//真的
现在您的foo
实例可以访问Bar
class Foo {
constructor(instance) {
this.instance = instance
}
}
class Bar {
@observable isLoading = false;
@observable data = null;
@action
getData() {
this.isLoading = true;
return axios.get('/foo').then((data) => {
this.isLoading = false;
this.data = data;
}).catch(e => {
this.isLoading = false;
});
}
}
const foo = new Foo(new Bar());
// in react
const MyComponent = ({ foo }) => (
<div>
{foo.instance.isLoading && <Spinner />}
<button onClick={foo.instance.getData}>
will call Bar action from Foo store
</button>
</div>
);
export default lodash.flowRight(
mobx.inject((stores) => ({ foo: stores.fooStore })),
mobx.observer
)(MyComponent)
class-Foo{
构造函数(实例){
this.instance=instance
}
}
分类栏{
@可观察到的孤岛负载=假;
@可观测数据=零;
@行动
getData(){
this.isLoading=true;
返回axios.get('/foo')。然后((数据)=>{
this.isLoading=false;
这个数据=数据;
}).catch(e=>{
this.isLoading=false;
});
}
}
const foo=new foo(new Bar());
//反应
常量MyComponent=({foo})=>(
{foo.instance.isLoading&&}
将从Foo store调用Bar操作
);
导出默认的lodash.flowRight(
mobx.inject((stores)=>({foo:stores.fooStore})),
mobx.observer
)(MyComponent)
在使用生成器的示例中,您不能使用胖箭头,因此这个
不再绑定到您的类实例,这就是它未定义的原因。使用承诺和粗箭解决了这个问题
class Foo {
constructor(instance) {
this.instance = instance
}
}
class Bar {
@observable isLoading = false;
@observable data = null;
@action
getData() {
this.isLoading = true;
return axios.get('/foo').then((data) => {
this.isLoading = false;
this.data = data;
}).catch(e => {
this.isLoading = false;
});
}
}
const foo = new Foo(new Bar());
// in react
const MyComponent = ({ foo }) => (
<div>
{foo.instance.isLoading && <Spinner />}
<button onClick={foo.instance.getData}>
will call Bar action from Foo store
</button>
</div>
);
export default lodash.flowRight(
mobx.inject((stores) => ({ foo: stores.fooStore })),
mobx.observer
)(MyComponent)