4
我收到錯誤「Redux操作必須是普通對象,使用自定義中間件進行異步操作。」用下面的代碼。Redux Actions必須是普通對象。使用自定義中間件進行異步操作
export const getFriends =() => async(): Action => {
const requestConfig = {
httpMethod: 'GET',
version: 'v2.7',
};
let hasMore = false;
let friends = [];
do {
const infoRequest = new GraphRequest(
'/me/friends',
requestConfig,
(error, result) => {
if (error) {
alert('Error fetching data facebook friends');
} else {
result.data.forEach((value) => {
friends.push(value)
});
if (result.paging && result.paging.next) {
hasMore = true;
requestConfig.parameters.after = result.paging.cursors.after;
} else {
hasMore = false;
}
}
});
await new GraphRequestManager().addRequest(infoRequest).start();
} while (hasMore);
return {
type: 'GET_FRIENDS',
payload: friends // this is empty because there is no await on GraphAPI
};
};
如果我刪除了異步和等待,朋友返回是空的,因爲函數調用返回之前GraphAPI調用返回
export const getFriends =() =>(): Action => {
const requestConfig = {
httpMethod: 'GET',
version: 'v2.7',
};
let hasMore = false;
let friends = [];
do {
const infoRequest = new GraphRequest(
'/me/friends',
requestConfig,
(error, result) => {
if (error) {
alert('Error fetching data facebook friends');
} else {
result.data.forEach((value) => {
friends.push(value)
});
if (result.paging && result.paging.next) {
hasMore = true;
requestConfig.parameters.after = result.paging.cursors.after;
} else {
hasMore = false;
}
}
});
new GraphRequestManager().addRequest(infoRequest).start();
} while (hasMore);
return {
type: 'GET_FRIENDS',
payload: friends // this is empty because there is no await on GraphAPI
};
};
是的,我正在使用redux-thunk。看到我做的同時。我需要等待,因爲這樣做。 GraphAPI不會一次返回整個回報,所以我必須分頁。我怎麼做? – user43286
爲了跟上該代碼片段,redux-thunk非常棒,因爲您可以從同一個動作分派多個事件。因此,您可以派發事件來指示加載過程的開始,然後在每次接收數據時調度ADD_FRIENDS方法,而不是等到結束。不需要返回任何東西,只需要在需要時實際調度()簡單對象操作 –
但是,while循環退出。 – user43286