我刚接触React + MobX,所以我还不完全了解它们的工作原理。
我希望仅在我转到getUserDataFromAPI()
并且加载组件ProfileStore
时才执行函数http://localhost:3000/profile
(在ProfileComponent
中)。
这就是我现在拥有的:
几个存储都在rootStore中初始化。
RootStore.js
class RootStore {
constructor() {
this.profileStore = new ProfileStore(this)
[other randomStores]
}
}
然后,在ProfileStore.js
中,我有:
ProfileStore.js
constructor(rootStore) {
this.rootStore = rootStore
runInaction('Load Profile',async () => {
await this.getUserDataFromAPI()
});
}
我仍然不知道runInaction的作用,但是主要的问题是ProfileStore's constructor
被执行而不管我要加载的组件是什么,因为它是用rootStore
初始化的。
如何使该函数仅在导航到/profile
并且加载Profile Component
时才能执行?