我收到错误“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
};
};
1 回答
错误意味着它听起来是什么样的 . Redux期待一个普通的对象 . 我看到用redux-thunk标记的问题 . 如果你正在使用redux-thunk,也许你没有正确设置中间件的商店 . 如果您没有使用redux-thunk,那么我会推荐它作为调度异步操作的首选库 .
这将为您提供有关调度非常规对象的redux操作的深刻见解 . How to dispatch a Redux action with a timeout?
编辑:你错过了实际的调度,并试图简单地返回普通对象...需要返回一个调度......类似于以下内容(没有测试,但应该让你关闭):