ReactJS - 等待动作在 componentDidMount 中完成
ReactJS - waiting for action to finish within componentDidMount
有问题的代码如下。我在 componentDidMount
中有一个异步 UserActions
调用,之后我立即从这个操作填充的 UserStore
中查找用户信息。显然,我不能依赖 UserStore.isLargeAccess()
的定义。将依赖于操作的代码放在回调中是最好的约定,还是我错过了一些更大的设计选择?
componentDidMount() {
this.changeListener = this._onChange.bind(this);
UserStore.addChangeListener(this.changeListener);
OrganizationStore.addChangeListener(this.changeListener);
// Fetch user info
UserActions.get(AuthStore.username);
// UserStore.isLargeAccess() is undefined here,
// because the previous action has not finished.
if (UserStore.isLargeAccess()) {
OrganizationActions.getUsers(this.state.organization);
}
if (UserStore.isGlobalAccess()) {
OrganizationActions.getOrganizations();
}
}
它应该如何工作(如果我理解你的流程):
- 您应该为每个商店注册不同的回调(否则您不知道哪个商店发出事件)
- 你开始一些异步工作。
- 异步工作完成后,它会使用来自异步工作的一些数据调度操作
- 您的商店 UserStore 和 OrganizationStore 监听这个动作,当他们收到它时,他们会做一些工作并发出变化。
- 当它们发出变化时,它们会从您的组件调用回调。在每个回调中,您知道哪个商店调用它,因此您知道从哪个商店获取数据。
有问题的代码如下。我在 componentDidMount
中有一个异步 UserActions
调用,之后我立即从这个操作填充的 UserStore
中查找用户信息。显然,我不能依赖 UserStore.isLargeAccess()
的定义。将依赖于操作的代码放在回调中是最好的约定,还是我错过了一些更大的设计选择?
componentDidMount() {
this.changeListener = this._onChange.bind(this);
UserStore.addChangeListener(this.changeListener);
OrganizationStore.addChangeListener(this.changeListener);
// Fetch user info
UserActions.get(AuthStore.username);
// UserStore.isLargeAccess() is undefined here,
// because the previous action has not finished.
if (UserStore.isLargeAccess()) {
OrganizationActions.getUsers(this.state.organization);
}
if (UserStore.isGlobalAccess()) {
OrganizationActions.getOrganizations();
}
}
它应该如何工作(如果我理解你的流程):
- 您应该为每个商店注册不同的回调(否则您不知道哪个商店发出事件)
- 你开始一些异步工作。
- 异步工作完成后,它会使用来自异步工作的一些数据调度操作
- 您的商店 UserStore 和 OrganizationStore 监听这个动作,当他们收到它时,他们会做一些工作并发出变化。
- 当它们发出变化时,它们会从您的组件调用回调。在每个回调中,您知道哪个商店调用它,因此您知道从哪个商店获取数据。