【发布时间】:2017-10-02 22:28:15
【问题描述】:
我正在使用redux-thunk 来管理一些副作用。问题如下。在我的 react 组件中的某个地方,我有一个函数负责在组件安装或获取新的 props 时获取所有必要的数据,即fetchRequiredData()。
在fetchRequiredData() 内,我正在遍历一个数组,因为每个键都需要获取一些数据。我需要能够有一个过度的承诺,只有当.map() 中的承诺得到解决时才会解决。如果我没有这个页面会遇到麻烦,因为它会尝试渲染它不能渲染的东西。
简化代码示例
export const fetchRequiredData = (requiredAccounts) => (dispatch) => {
// How to wrap the promises inside the .map() into 1 "big" promise?
requiredAccounts.map(account => {
dispatch(fetchAccount(account)); // Returns a promise
});
}
在我的组件中,我应该能够执行以下操作
class Accounts extends Component {
constructor(props) {
super(props);
this.state = {
pending: true;
}
}
componentDidMount() {
this.setState({pending: true});
this.props.fetchRequiredData().then(() => this.setState({pending: false}));
}
componentWillUpdate(nextProps, nextState) {
this.setState({pending: true});
this.props.fetchRequiredData().then(() => this.setState({pending: false}));
}
}
【问题讨论】:
标签: javascript promise redux redux-thunk