【问题标题】:How to execute a function after loading a component in Reactjs + MobX?在 Reactjs + MobX 中加载组件后如何执行函数?
【发布时间】: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


    【解决方案1】:

    你想要的是一个componentDidMount 方法。

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

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

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

    【讨论】:

    • 那么,我应该从 RootStore 中删除 ProfileStore 声明并将 componentDidMount() 放在 Component 文件的开头吗?我在 MobX 文档中读到,使用单个 rootStore 来初始化它们是很好的做法。同样,很可能我没有正确理解它。你怎么看?
    • 我会将它保存在 componentDidMount 中,因为在加载组件时会调用它,如果需要,您可以将构造函数保持原样。构造函数在组件被挂载到 DOM 之前就被调用了。
    • 我不明白。我在rootStoreProfileComponent 中创建new ProfileStore(this),不是吗?否则它将被复制,getUserDataFromAPI() 函数将运行两次。我应该从构造函数中删除该函数还是应该将它留在那里?抱歉问了这么多问题。一旦澄清这一点,我将尽一切办法回答问题
    • 哦,很抱歉没有说清楚。我将从构造函数中删除对this.profileStore = new ProfileStore(this) 的特定调用,并在ProfileComponentcomponentDidMount 方法中执行ProfileStore 创建。这样,ProfileStore(this) 调用将仅在 ProfileComponent 加载时运行。
    猜你喜欢
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    相关资源
    最近更新 更多