gpt4 book ai didi

asynchronous - Redux Actions 必须是普通对象。使用自定义中间件进行异步操作

转载 作者:行者123 更新时间:2023-12-04 21:08:01 24 4
gpt4 key购买 nike

我收到错误“Redux 操作必须是普通对象。使用自定义中间件进行异步操作。”用下面的代码。

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
};
};

如果我删除异步并等待,返回的 friend 是空的,因为函数调用在 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 期待一个普通对象。我看到用 redux-thunk 标记的问题。如果您使用的是 redux-thunk,可能您没有正确设置中间件的商店。如果您不使用 redux-thunk,那么我会推荐它作为调度异步操作的首选库。

这将使您深入了解调度非普通对象的 redux 操作。
How to dispatch a Redux action with a timeout?

编辑:你错过了实际的调度,并试图简单地返回普通对象......需要返回调度......类似于以下内容(尚未测试,但应该让你接近):

    export const getFriends = () => {
return (dispatch) => {
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;
return dispatch({
type: 'GET_FRIENDS',
payload: friends
});
}
}
});
await new GraphRequestManager().addRequest(infoRequest).start();
} while (hasMore);
}
};

关于asynchronous - Redux Actions 必须是普通对象。使用自定义中间件进行异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41172834/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com