所以我试图在反应上构建这个动作,我需要它作为一个承诺。 操作成功,我收到服务器的响应,但我也收到错误说:
VM89852:98 Uncaught TypeError: Cannot read property 'then' of undefined.
行动:
export const fetchAllAccounts = (token, dispatch) => {
return new Promise((resolve, reject) => {
fetchAccountsStart((dispatch));
return axios.get(`${API_URL}/accounts`, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
}).then(
(response) => {
fetchAccountsSuccess(dispatch, response.data);
resolve(response.data);
},(error) => {
fetchAccountsFailed(dispatch, error.data);
reject(error.data);
},
);
});
};
还有关于我如何称呼此行为的方法。
this.props.fetchAllAccounts(token)
.then((data) => {
console.log("#".repeat(120));
console.log(data);
console.log("#".repeat(120));
}).catch((error) => {
console.log("#".repeat(120));
console.log(error);
console.log("#".repeat(120));
});
答案 0 :(得分:1)
你的评论
继承了mapDispatchToProps的电话......
fetchAllAccounts: (token) => { fetchAllAccounts(token, dispatch) },
评论中有你的问题。这要么是
fetchAllAccounts: (token) => { return fetchAllAccounts(token, dispatch) },
或
fetchAllAccounts: (token) => fetchAllAccounts(token, dispatch),
了解使用箭头功能,如果您使用{}
需要返回,则没有隐含的回报
作为奖励 - 删除promise构造函数反模式
export const fetchAllAccounts = (token, dispatch) => {
fetchAccountsStart((dispatch));
return axios.get(`${API_URL}/accounts`, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
}).then(
(response) => {
fetchAccountsSuccess(dispatch, response.data);
return response.data;
}, (error) => {
fetchAccountsFailed(dispatch, error.data);
throw error.data;
// Borrowed from @T.J.Crowder's pastebin :p
// Note that it's best to reject or throw an Error instance,
// not other types; e.g., `throw new Error(error.data)` or
// `return Promise.reject(new Error(error.data))`
},
);
};