在Reactjs + MobX中加载组件后如何执行函数? RootStore.js ProfileStore.js

我刚接触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时才能执行?

yujunjie19860211 回答:在Reactjs + MobX中加载组件后如何执行函数? RootStore.js ProfileStore.js

您想要的是componentDidMount方法。

componentDidMount(){
  this.profileStore = new ProfileStore(this)
}

将在组件MOUNT上执行一次,而不是在组件创建上执行。

https://reactjs.org/docs/react-component.html#componentdidmount

本文链接:https://www.f2er.com/3152609.html

大家都在问