Redux thunk - 嵌套调度函数/动作
Redux thunk - Nesting dispatched functions / actions
我正在使用 redux-thunk 在我的 React 应用程序中执行异步操作,如下所示:
export const fetchImages = (objects) => dispatch => {
const promises = objects.map(obj => axios
.get(`${API_URL}/files/${obj.img ? vendor.img : 'default.png'}`, {responseType: 'arraybuffer'})
.then( res => obj.imgData = 'data:;base64,' + convertArrayBufferToBase64(res.data))
);
return Promise.all(promises).then (() => Promise.resolve(objects));
}
当我在我的任何组件中使用它时,它工作得很好。但是,如果我像这样在另一个动作中使用它:
export const fetchAllObjects = () => dispatch => axios.get(`${API_URL}/objects?limit=50`)
.then(res => fetchImages(res.data.docs).then(objects =>
dispatch({
type: FETCH_ALL_OBJECTS,
payload: objects
});
));
它失败了。我希望它 return 一个承诺,但是它 returns "dispatch => ..." 因此 then()
在 returned 值上失败。
我刚刚注意到 fetchImages
是一个函数 returns 一个函数:
export const fetchAllObjects = () => dispatch => axios.get(`${API_URL}/objects?limit=50`)
.then(res => fetchImages(res.data.docs)(dispatch).then(objects =>
dispatch({
type: FETCH_ALL_OBJECTS,
payload: objects
});
));
我正在使用 redux-thunk 在我的 React 应用程序中执行异步操作,如下所示:
export const fetchImages = (objects) => dispatch => {
const promises = objects.map(obj => axios
.get(`${API_URL}/files/${obj.img ? vendor.img : 'default.png'}`, {responseType: 'arraybuffer'})
.then( res => obj.imgData = 'data:;base64,' + convertArrayBufferToBase64(res.data))
);
return Promise.all(promises).then (() => Promise.resolve(objects));
}
当我在我的任何组件中使用它时,它工作得很好。但是,如果我像这样在另一个动作中使用它:
export const fetchAllObjects = () => dispatch => axios.get(`${API_URL}/objects?limit=50`)
.then(res => fetchImages(res.data.docs).then(objects =>
dispatch({
type: FETCH_ALL_OBJECTS,
payload: objects
});
));
它失败了。我希望它 return 一个承诺,但是它 returns "dispatch => ..." 因此 then()
在 returned 值上失败。
我刚刚注意到 fetchImages
是一个函数 returns 一个函数:
export const fetchAllObjects = () => dispatch => axios.get(`${API_URL}/objects?limit=50`)
.then(res => fetchImages(res.data.docs)(dispatch).then(objects =>
dispatch({
type: FETCH_ALL_OBJECTS,
payload: objects
});
));