我正在尝试构建一个React App,它在初始加载时从7个api提取数据,然后将所有数据存储在Redux中,以在该应用程序中使用。我对React很陌生,并且有点编码菜鸟。
我的第一个应用页面上有一个调度功能,该功能会在componentDidMount()上触发并在以下操作中运行fetchData()函数。
export function getDataPending(actionType) {
return {
type: "FETCH_" + actionType.toUpperCase() + "_PENDING"
};
}
export function getDataSuccess(actionType, data) {
return {
type: "FETCH_" + actionType.toUpperCase() + "_FULFILLED",
payload: data
};
}
export function getDataFailure(actionType, data) {
return {
type: "FETCH_" + actionType.toUpperCase() + "_REJECTED",
payload: data
};
}
//Sub data fetches
export function fetchNicSalts() {
return dispatch => {
dispatch(getDataPending("nic_salt"));
axios
.get(
"API_FEED"
)
.then(response => {
dispatch(getDataSuccess("nic_salt", response));
})
.catch(err => {
dispatch(getDataFailure("nic_salt", err));
});
};
}
export function fetchFreebase() {
return dispatch => {
dispatch(getDataPending("freebase"));
axios
.get(
"API_FEED"
)
.then(response => {
dispatch(getDataSuccess("freebase", response));
})
.catch(err => {
dispatch(getDataFailure("freebase", err));
});
};
}
//Main data fetch
export function fetchData() {
return dispatch => {
dispatch(getDataPending("data"));
dispatch(fetchFreebase());
dispatch(fetchNicSalts());
dispatch(getDataSuccess("data", null));
};
}
目前只有两次api提取,因为我试图让它们运行异步。 理想情况下,我要进行的调度将按此顺序运行。 FETCH_DATA_PENDING FETCH_FREEBASE_PENDING FETCH_FREEBASE_FULFILLED FETCH_NIC_SALT_PENDING FETCH_NIC_SALT_FULFILLED ****下一个api ***** FETCH_DATA_FULFILLED
此刻数据正以错误的顺序存储。请查看当前订单的图片。
正如我所说,我是自学成才的,不确定自己是否走对路,我们欢迎您提出任何建议。 TIA。
答案 0 :(得分:1)
您需要使fetchFreebase和fetchNicSalts返回axios调用,以便您可以在fetchData操作中等待它们。
这看起来像这样
export function getDataPending(actionType) {
return {
type: "FETCH_" + actionType.toUpperCase() + "_PENDING"
};
}
export function getDataSuccess(actionType, data) {
return {
type: "FETCH_" + actionType.toUpperCase() + "_FULFILLED",
payload: data
};
}
export function getDataFailure(actionType, data) {
return {
type: "FETCH_" + actionType.toUpperCase() + "_REJECTED",
payload: data
};
}
//Sub data fetches
export function fetchNicSalts() {
return dispatch => {
dispatch(getDataPending("nic_salt"));
return axios
.get(
"API_FEED"
)
.then(response => {
dispatch(getDataSuccess("nic_salt", response));
})
.catch(err => {
dispatch(getDataFailure("nic_salt", err));
});
};
}
export function fetchFreebase() {
return dispatch => {
dispatch(getDataPending("freebase"));
return axios
.get(
"API_FEED"
)
.then(response => {
dispatch(getDataSuccess("freebase", response));
})
.catch(err => {
dispatch(getDataFailure("freebase", err));
});
};
}
//Main data fetch
export function fetchData() {
return async (dispatch) => {
dispatch(getDataPending("data"));
await dispatch(fetchFreebase());
await dispatch(fetchNicSalts());
dispatch(getDataSuccess("data", null));
};
}