我正在尝试开发一个应用程序,该应用程序显示给定关键字的Unsplash照片。我设法使用unsplash.js提取了特定的照片。在我的动作中,我有几个动作创建者:
export const fetchPhotos = () => ({
type: FETCH_PHOTOS
});
export const receivePhotos = term => {
const unsplash = new Unsplash({
applicationId:
"id",
secret: "secret",
callbackUrl: "callback"
});
console.log(term);
const response = unsplash.search
.photos(term, 1, 20)
.then(toJson)
.then(json => json)
.then(json => json)
console.log(response.then(results => results));
return {
type: RECEIVE_PHOTOS,
payload: response
};
}
export const unsplash = (term) => dispatch => {
console.log(term);
dispatch(fetchPhotos());
setTimeout(() => {
dispatch(receivePhotos(term));
console.log("dispatching")
return Promise.resolve();
}, 1000)
}
然后我的减速器做
:const initialState = {
isFetching: false,
sortDirection: null,
sortKey: null,
items: []
}
export default function(state = initialState, action) {
switch (action.type) {
case FETCH_PHOTOS:
console.log(state, "Fetch photos reducer");
return {
...state,
isFetching: true
};
case RECEIVE_PHOTOS:
console.log("Receive photos reducer", action.payload)
return {
...state,
isFetching: false,
items: action.payload
};
case SET_SORT:
return {
...state,
sortKey: action.sortKey,
sortDirection: action.sortDirection
};
default:
return state;
}
}
但是,当receivePhotos操作创建者调用API时,我有一个需要解决的诺言,才能使整个应用程序正常工作。我的获取照片还原程序是在控制台上记录操作,然后出现Promise,但始终处于待处理状态。然后,我的receivePhotos动作创建者将分派到reducer,我可以看到这是一个Promise:
我如何履行这一诺言?
答案 0 :(得分:2)
在下面的代码中,您向response
分配了一个诺言,然后向该console.log
分配了诺言,然后在payload
设置为该诺言的情况下返回操作。
const response = unsplash.search
.photos(term, 1, 20)
.then(toJson)
.then(json => json)
.then(json => json)
console.log(response.then(results => results));
return {
type: RECEIVE_PHOTOS,
payload: response
};
dispatch(receivePhotos(term));
然后分派该动作,同时仍然以有效载荷作为承诺。 也许如果您有可以处理它的中间件,这将起作用。
这种对dispatch的使用表明您正在使用redux-thunk。
在这种情况下,您应该对receivePhotos
进行同样的操作,包括fetchPhotos
调用,并退出unsplash
操作。
const unsplashClient = new Unsplash({
applicationId:
"id",
secret: "secret",
callbackUrl: "callback"
});
export const receivePhotos = term => dispatch => {
dispatch(fetchPhotos());
return unsplashClient.search
.photos(term, 1, 20)
.then(toJson)
.then(json => dispatch({
type: RECEIVE_PHOTOS,
payload: json
});
}
最后,我建议对动作和(相关的缩减器)进行一些重构,例如:
const unsplashClient = new Unsplash({
applicationId:
"id",
secret: "secret",
callbackUrl: "callback"
});
export const fetchingPhotos = payload => ({
type: FETCHING_PHOTOS, payload
});
export const setPhotos = payload => ({
type: SET_PHOTOS, payload
});
export const fetchPhotos = term => dispatch => {
dispatch(fetchingPhotos(true));
return unsplashClient.search
.photos(term, 1, 20)
.then(toJson)
.then(json => {
dispatch(setPhotos(json));
dispatch(fetchingPhotos(false));
});
}