gpt4 book ai didi

javascript - 为什么它从这个 redux dispatch 返回 undefined ?

转载 作者:行者123 更新时间:2023-11-30 14:30:33 24 4
gpt4 key购买 nike

我获取了一个名为 project 的对象,其中包含一个数组 QS 和两个 id,我想为它们中的每一个分配一个新的操作。第一次调度正确返回数组

.then((project) => dispatch(lastProjectFetchDataSuccess(project.qs)))

但另外两个确实返回未定义?我正在获取的对象:

{qs:[objects],qpId: "an ID",projectId: "another ID"}

Action :

export function lastProjectFetchData(url, owner) {
return dispatch => {
dispatch(lastProjectIsLoading(true));
fetch(url, {
method: "POST",
body: JSON.stringify({
owner: "charlie",
projectName: "charliesprojekt"
}),
headers: { "Content-Type": "application/json" }
})
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}

dispatch(lastProjectIsLoading(false));

return response;
})
.then(response => response.json())
.then(project => dispatch(lastProjectFetchDataSuccess(project.qs))) // returns the array
.then(project => dispatch(qpIdFetchDataSuccess(project.qpId))) // returns undefined
.then(project => dispatch(projectIdFetchDataSuccess(project.projectId))) // returns undefined
.catch(() => dispatch(lastProjectHasErrored(true)));
};
}

最佳答案

您没有从第三个 then 回调中返回 project,因此以下 then 回调将得到 undefined.

你可以这样做:

.then(response => response.json())
.then(project => {
dispatch(lastProjectFetchDataSuccess(project.qs));
return project;
})
.then(project => {
dispatch(qpIdFetchDataSuccess(project.qpId))
return project;
})
.then(project => {
dispatch(projectIdFetchDataSuccess(project.projectId));
return project;
})
.catch(() => dispatch(lastProjectHasErrored(true)));

您也可以在同一个 then 回调中完成所有操作:

.then(response => response.json())
.then(project => {
dispatch(lastProjectFetchDataSuccess(project.qs));
dispatch(qpIdFetchDataSuccess(project.qpId));
dispatch(projectIdFetchDataSuccess(project.projectId));
})
.catch(() => dispatch(lastProjectHasErrored(true)));

关于javascript - 为什么它从这个 redux dispatch 返回 undefined ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51265297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com