【发布时间】:2020-03-02 21:10:04
【问题描述】:
我是使用 React + MobX 的新手,所以我还不完全了解它们是如何工作的。
我希望函数getUserDataFromAPI()(在ProfileStore中)仅在我转到http://localhost:3000/profile并加载组件ProfileComponent时才执行。
这是我现在拥有的:
在 rootStore 中初始化了几个 Store。
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 时执行?
【问题讨论】:
标签: reactjs store mobx mobx-react