如何在 Reactjs + MobX 中加载组件后执行功能?

How to execute a function after loading a component in Reactjs + MobX?

我是 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.[=21= 初始化的]

如何让该函数仅在我导航到 /profile 并且 Profile Component 已加载时执行?

你想要的是componentDidMount方法。

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

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

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