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