【发布时间】:2021-01-07 02:59:12
【问题描述】:
我从应用程序的后端获取了一些数据,但我很难正确返回状态。 代码:
if (action.type === actionTypes.getList) {
const id = action.payload.userId;
Axios.post(`${apiUrl}/lists`, {
userId: id,
})
.then((response) => {
const newLists = response.data;
return { ...listState, lists: newLists };
})
.catch((e) => {
console.log("There has been error: ", e);
});
}
在这个状态下,reducer 状态是未定义的,我得到它是因为我没有从主 If 语句返回任何内容。
if (action.type === actionTypes.getList) {
const id = action.payload.userId;
const newLists = Axios.post(`${apiUrl}/lists`, {
userId: id,
})
.then((response) => {
const res = response.data;
return res
})
.catch((e) => {
console.log("There has been error: ", e);
});
return { ...listState, lists: newLists };
}
这里我的减速器状态是空对象,我在控制台中得到 Promise { : "pending" }。在异步函数完成后,有什么方法可以调用主返回语句吗?或者有什么其他方法可以解决这个问题?
【问题讨论】:
-
您不能等待同步函数中的异步结果。因此,您也应该使周围的函数异步,并在您的第一个 sn-p 中返回或等待您从
Axios.post()获得的 Promise。 -
当数据异步到达时需要dispatch一个新事件
-
是的,我做到了,谢谢你的建议!
标签: javascript reactjs asynchronous async-await reducers